簡體   English   中英

從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 $0.tag == 23 {
            $0.removeFromSuperview()
        }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM