ios - 如何使 UITextView 的掩码与其框架保持同步

标签 ios swift

这是说明问题的 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/

相关文章:

ios - 如何通过按钮关闭并重新打开 viewController?

ios - 为应用程序设置设计表格 View 的最佳做法?

android - 如何在 Xamarin.Forms 中监控应用用户的在线状态

ios - 'NSInternalInconsistencyException',原因 : 'Requested the number of rows for section (0) which is out of bounds.'

ios - 使用两个字典键基于日期和时间对数组进行排序

ios - Swift- EXC_CRASH (SIGABRT) 如何使用此堆栈跟踪查找异常

c++ - 在 Swift 中使用 C++ 模板

ios - 从扩展目标访问主 App 类 - iOS

swift 3 : TPKeyboardAvoidingScrollView not working properly on one UITextField in UITableViewCell

arrays - unshare() 和 copy() 有什么区别?