从TextField删除子层

时间:2018-10-11 17:47:46

标签: ios swift uitextfield calayer uitextborderstyle

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

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

1 个答案:

答案 0 :(得分:0)

您可以尝试使用.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()
        }
    }
  }
}