Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

前端 未结 22 2391
自闭症患者
自闭症患者 2020-11-27 09:19

I would like to keep the border at the bottom part only in UITextField. But I don\'t know how we can keep it on the bottom side.

Can you please advise m

22条回答
  •  天命终不由人
    2020-11-27 09:54

    None of these solutions really met my expectations. I wanted to subclass the TextField since I don't want to set the border manually all the time. I also wanted to change the border color e.g. for an error. So here's my solution with Anchors:

    class CustomTextField: UITextField {
    
        var bottomBorder = UIView()
    
        override func awakeFromNib() {
    
                // Setup Bottom-Border
    
                self.translatesAutoresizingMaskIntoConstraints = false
    
                bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
                bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color
                bottomBorder.translatesAutoresizingMaskIntoConstraints = false
    
                addSubview(bottomBorder)
    
                bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
                bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
                bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
                bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength
    
        }
    }
    

    ---- Optional ----

    To change the color add sth like this to the CustomTextField Class:

    @IBInspectable var hasError: Bool = false {
        didSet {
    
            if (hasError) {
    
                bottomBorder.backgroundColor = UIColor.red
    
            } else {
    
                bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)
    
            }
    
        }
    }
    

    And to trigger the Error call this after you created an instance of CustomTextField

    textField.hasError = !textField.hasError
    

    Hope it helps someone ;)

提交回复
热议问题