首页 > 解决方案 > 无法从 UITextField 中删除 CALayer

问题描述

所以,我有这个自定义UITextField,我有两种方法来添加CALayer和删除,CALayer但删除不起作用。

@IBDesignable class AppTextField : UITextField {

    private let bottomLine = CALayer()

    override func layoutSubviews() {
        self.font = .systemFont(ofSize: 20)
        self.addBottomLine()
        self.clearButtonMode = .unlessEditing
        super.layoutSubviews()
    }

    func removeBttomLine() {
        bottomLine.removeFromSuperlayer()
    }

    private func addBottomLine() {
        bottomLine.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.height + 4), size: CGSize(width: self.frame.width, height: 1))
        bottomLine.backgroundColor = UIColor.init(hexString: "#DCCFCA")?.cgColor
        self.borderStyle = .none
        self.layer.addSublayer(bottomLine)
    }
}

标签: iosswiftcalayer

解决方案


原因可能是因为该layoutSubviews方法被多次调用并且层被多次添加。如果您使用情节提要或使用或自定义仅调用一次的方法,请尝试将addBottomLine方法移动到方法。这是一个例子:required init?(coder:)init(frame:)init

@IBDesignable class AppTextField : UITextField {

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        addBottomLine()
    }
}

推荐阅读