-2
在swift中,有沒有辦法只爲UIView的頂邊設置邊框?如何爲UIView的邊緣之一設置邊框
在swift中,有沒有辦法只爲UIView的頂邊設置邊框?如何爲UIView的邊緣之一設置邊框
有很多方法,但自己畫邊界可能會提供更多的控制。我會建議繼承UIView
並使用CAShapeLayer
來完成此操作。
某事(用斯威夫特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
你可以添加一個子視圖,作爲一個邊框行事。 –