1

I need two functions, One to add a bottom boarder and one to remove a bottom boarder. How can I remove this boarder I have created?

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(){        
    }
}
giusti
  • 3,156
  • 3
  • 29
  • 44

1 Answers1

2

You can try to remove the layer with .removeFromSuperlayer() so hold a reference to it

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

for safety that you may add other sublayers

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()
        }
    }
  }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Would I place this in my Extension? –  Oct 11 '18 at 18:01
  • This worked perfectly :) Thanks so much! I only have one sublayer so the first solution of fine for me –  Oct 11 '18 at 18:35