如何仅为UIView的一个边设置边框

时间:2016-09-25 20:54:36

标签: swift uiview

在swift中,有没有办法只为UIView的顶部设置边框?

1 个答案:

答案 0 :(得分:4)

有很多方法,但自己绘制边框可能会提供更多控制。我建议继承UIView并使用CAShapeLayer来完成此任务。

使用Swift 3的效果:

import UIKit

class TopBorderedView: UIView {
   //decalare a private topBorder
   fileprivate weak var topBorder: CAShapeLayer?

   //declare a border thickness to allow outside access to setting it
    var topThickness: CGFloat = 1.0 {
        didSet {
            drawTopBorder()
        }  
    }

    //declare public color to allow outside access
    var topColor: UIColor = UIColor.lightGray {
        didSet {
            drawTopBorder()
        }
    }

   //implment the draw method
   fileprivate func drawTopBorder() {
      let start = CGPoint(x: 0, y: 0)
      let end = CGPoint(x: bounds.width, y: 0)
      removeIfNeeded(topBorder)
      topBorder = addBorder(from: start, to: end, color: topColor, thickness: topThickness)
   }

   //implement a private border drawing method that could be used for border on other sides if desired, etc..
   fileprivate func addBorder(from: CGPoint, to: CGPoint, color: UIColor, thickness: CGFloat) -> CAShapeLayer {
            let border = CAShapeLayer()
            let path = UIBezierPath()
            path.move(to: start)
            path.addLine(to: end)
            border.path = path.cgPath
            border.strokeColor = color.cgColor
            border.lineWidth = thickness
            border.fillColor = nil
            layer.addSublayer(border)
            return border
    }

    //used to remove the border and make room for a redraw to be autolayout friendly
    fileprivate func removeIfNeeded(_ border: CAShapeLayer?) {
        if let bdr = border {
            bdr.removeFromSuperlayer()
        }
    }

    //override layoutSubviews() (probably debatable) and call the drawTopBorder method to draw and redraw if needed
    override func layoutSubviews() {
        super.layoutSubviews()
        drawTopBorder()
    }
}

为了在故事板的上下文中实现最大的可重用性 - 我还要看看如何使用@IBDesignable和@IBInspectable来处理常见的UI模式。对于一个体面的介绍,结帐NSHipster: IBDesignable and IBInspectable