ios - 无法从 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)
}
}
解决方案
原因可能是因为该layoutSubviews
方法被多次调用并且层被多次添加。如果您使用情节提要或使用或自定义仅调用一次的方法,请尝试将addBottomLine
方法移动到方法。这是一个例子:required init?(coder:)
init(frame:)
init
@IBDesignable class AppTextField : UITextField {
required init?(coder: NSCoder) {
super.init(coder: coder)
addBottomLine()
}
}
推荐阅读
- c++ - 如何将 C/C++/Rust 编译器默认十进制数字基数设置为十六进制基数?
- excel - VBA 将数据粘贴到下一行
- c - 如何让 C 程序在文件内容中添加行号。例如,“1.#include
2.#包括 “, ETC。? - html - 在悬停时禁用蜂检测元素
- chisel - 扩展数据类型或添加信息的方式
- laravel - 为什么 laravel 任务不使用 cron 运行?
- vue.js - laravel 8.x 中的 jet-application-mark
- javascript - 使用 Node 时未从查询返回数据,但从控制台返回数据 | 涌入数据库
- javascript - JS .includes() 具有多个数组值?
- r - 绘制按分类变量分组的变量箱线图