我需要在UILable中为动画调整 mask ,但是这个layer.mask方法没有运行
class FirstView: UIView {
var showAbout: UILabel {
let label = UILabel()
...
return label
}
var showAboutMask: CAShapeLayer {
let layer = CAShapeLayer()
...
return layer
}
override init(frame: CGRect) {
super.init(frame: frame)
showAbout.layer.mask = showAboutMask
addSubview(showAbout)
}
}
标签显示但 mask 层不出现
最佳答案
看起来您正在修改 showAbout
的一个实例,然后将另一个实例添加为 subview 。发生这种情况是因为 showAbout
是一个 "computed property" .计算属性实际上并不存储值,而是在每次调用时计算该值(就像一个函数)。
You can verify this behavior by setting a breakpoint in the body of
showAbout
and note that it gets called twice.
正因为如此,在initializeViews
调用的时候
showAbout.layer.mask = showAboutMask
您计算一个 UILabel
实例并修改其层的 mask 。然后,当你调用
addSubview(showAbout)
您计算另一个 UILabel
实例(没有图层蒙版)并将其添加为 subview 。
计算属性有它们的用例,但在这里您可能想要存储 UILabel
实例。一种方法是懒惰地为其分配计算闭包的值,类似于 showAboutMask
的分配方式:
lazy var showAbout: UILabel = {
// same label creation as before
}()
关于swift - 如何在 Swift 中的 UILabel 上设置 CAShapeLayer 掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46467328/