我的观看的一些帧只能在调用layoutSubviews
之后设置:
class CustomButton: UIButton {
let border = CAShapeLayer()
init() {
super.init(frame: CGRectZero)
border.fillColor = UIColor.whiteColor().CGColor
layer.insertSublayer(border, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
}
}
因为我想在以后的状态中为border
制作动画,所以我只希望调用layoutSubviews
中的代码一次。为此,我使用以下代码:
var initial = true
override func layoutSubviews() {
super.layoutSubviews()
if initial {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
initial = false
}
}
我想知道是否有更好的方法可以做到这一点。一种更优雅和功能性的方式,无需使用额外的变量。
答案 0 :(得分:0)
有一种方法可以做到这一点而没有额外的变量(尽管也不是特别优雅)依赖于lazy static properties initialization:
class CustomButton: UIButton {
struct InitBorder {
// The static property definition
static let run: Void = {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
}()
}
let border = CAShapeLayer()
init() {
super.init(frame: CGRectZero)
border.fillColor = UIColor.whiteColor().CGColor
layer.insertSublayer(border, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
// The call which initializes the static property
let _ = InitBorder.run
}
}
答案 1 :(得分:-2)
let initial = false
override func layoutSubviews() {
super.layoutSubviews()
if initial {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
initial = false
}
}