因此,我具有此自定义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)
}
}
您在layoutSubviews()
中唯一要做的就是根据需要更新帧。
将在编辑字段[[NOT时显示红线,并在编辑字段[[IS时将其删除:
@IBDesignable class AppTextField : UITextField {
private let bottomLine = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
self.font = .systemFont(ofSize: 20)
self.backgroundColor = .white
self.clearButtonMode = .unlessEditing
self.borderStyle = .none
bottomLine.backgroundColor = UIColor.red.cgColor
addBottomLine()
}
override func layoutSubviews() {
super.layoutSubviews()
var r = bounds
r.origin.y = bounds.maxY
r.size.height = 4.0
bottomLine.frame = r
}
func removeBottomLine() {
bottomLine.removeFromSuperlayer()
}
private func addBottomLine() {
self.layer.addSublayer(bottomLine)
}
override func resignFirstResponder() -> Bool {
super.resignFirstResponder()
addBottomLine()
return true
}
override func becomeFirstResponder() -> Bool {
super.becomeFirstResponder()
removeBottomLine()
return true
}
}
@IBDesignable class AppTextField : UITextField {
required init?(coder: NSCoder) {
super.init(coder: coder)
addBottomLine()
}
}
装饰框
layoutSubviews
调用它的,所以它被多次调用,并且最后添加了多个图层,这就是为什么调用remove似乎不起作用的原因。为了使此代码起作用,您应该将部分添加到init(withCoder
,withFrame
或两者)。您可以通过设置颜色将其加入,因为它只能完成一次。下一部分是调整layoutSubviews
中的帧,这是必需的,因为图层无法进入自动布局。最后,您将创建,添加为子层并设置在init一次调用的零件,并在布局遍历中多次调用。现在,一次调用时将其删除-这次它将具有可见的效果。