从 TextField 中移除子层
Remove a sublayer from TextField
我需要两个函数,一个添加底部边框,一个删除底部边框。我怎样才能删除我创建的这个寄宿生?
extension UITextField {
func addBottomBorder(){
let bottomLine = CALayer()
bottomLine.frame = CGRect.init(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
bottomLine.backgroundColor = UIColor.white.cgColor
self.borderStyle = UITextBorderStyle.none
self.layer.addSublayer(bottomLine)
}
func removeBottomBorder(){
}
}
您可以尝试使用 .removeFromSuperlayer()
删除图层,因此保留对它的引用
extension UITextField {
func addBottomBorder(){
let bottomLine = CALayer()
bottomLine.frame = CGRect.init(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
bottomLine.backgroundColor = UIColor.red.cgColor
self.layer.addSublayer(bottomLine)
}
func removeBottomBorder() {
self.layer.sublayers?.first?.removeFromSuperlayer()
}
}
为了安全起见,您可以添加其他子层
extension UITextField {
func addBottomBorder(){
let bottomLine = UIView()
bottomLine.tag = 23
bottomLine.frame = CGRect.init(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
bottomLine.backgroundColor = UIColor.red
self.addSubview(bottomLine)
}
func removeBottomBorder() {
self.subviews.forEach {
if [=11=].tag == 23 {
[=11=].removeFromSuperview()
}
}
}
}
我需要两个函数,一个添加底部边框,一个删除底部边框。我怎样才能删除我创建的这个寄宿生?
extension UITextField {
func addBottomBorder(){
let bottomLine = CALayer()
bottomLine.frame = CGRect.init(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
bottomLine.backgroundColor = UIColor.white.cgColor
self.borderStyle = UITextBorderStyle.none
self.layer.addSublayer(bottomLine)
}
func removeBottomBorder(){
}
}
您可以尝试使用 .removeFromSuperlayer()
删除图层,因此保留对它的引用
extension UITextField {
func addBottomBorder(){
let bottomLine = CALayer()
bottomLine.frame = CGRect.init(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
bottomLine.backgroundColor = UIColor.red.cgColor
self.layer.addSublayer(bottomLine)
}
func removeBottomBorder() {
self.layer.sublayers?.first?.removeFromSuperlayer()
}
}
为了安全起见,您可以添加其他子层
extension UITextField {
func addBottomBorder(){
let bottomLine = UIView()
bottomLine.tag = 23
bottomLine.frame = CGRect.init(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
bottomLine.backgroundColor = UIColor.red
self.addSubview(bottomLine)
}
func removeBottomBorder() {
self.subviews.forEach {
if [=11=].tag == 23 {
[=11=].removeFromSuperview()
}
}
}
}