1

我需要两个功能,一个是添加底部边框,一个是删除底部边框。如何删除我创建的这个寄宿生?

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(){        
    }
}
4

1 回答 1

2

您可以尝试删除图层,.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 $0.tag == 23 {
            $0.removeFromSuperview()
        }
    }
  }
}
于 2018-10-11T17:53:23.907 回答