这是说明问题的 GIF:
这是我目前的代码,它只是将 UITextView 的顶部两个角四舍五入。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
let textView = UITextView(frame: CGRectMake(20, 20, self.view.frame.width - 40, 60))
textView.bounces = false
textView.backgroundColor = UIColor.grayColor()
let maskPath = UIBezierPath(
roundedRect: textView.bounds,
byRoundingCorners: (UIRectCorner.TopLeft | UIRectCorner.TopRight),
cornerRadii: CGSizeMake(8, 8)
)
let maskLayer = CAShapeLayer()
maskLayer.frame = textView.bounds
maskLayer.path = maskPath.CGPath
textView.layer.mask = maskLayer
self.view.addSubview(textView)
}
}
我尝试子类化 UITextView
并重写 layoutSubviews
,如下所示:
class TextView: UITextView {
var maskLayer: CAShapeLayer!
override func layoutSubviews() {
maskLayer.frame = bounds
}
}
但这以一个奇怪的动画结束:
我的问题是:如何使两者保持同步?
最佳答案
您在 layoutSubviews
中的解决方案是正确的。问题是对 Core Animation 层的更改是隐式动画的。您可以通过将帧更改包装在 CATransaction
中并设置禁用核心动画操作的事务属性来防止这种情况:
override func layoutSubviews() {
CATransaction.begin()
CATransaction.setDisableActions(true)
maskLayer.frame = bounds
CATransaction.commit()
}
关于ios - 如何使 UITextView 的掩码与其框架保持同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26560069/