改变uitextfield swift的底线边界

时间:2017-01-04 22:11:36

标签: ios swift uitextfield

我尝试使用以下代码更改边框属性:

class SimpleTextField: UITextField, UITextFieldDelegate {

      override func layoutSubviews() {
        super.layoutSubviews()

        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor.black.cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)

        border.borderWidth = width
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true

       self.delegate = self


    }

 func textFieldDidBeginEditing(_ textField: UITextField) {
        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor.green.cgColor
        border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)

        border.borderWidth = width
        textField.layer.addSublayer(border)
        textField.layer.masksToBounds = true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor.black.cgColor
        border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)

        border.borderWidth = width
        textField.layer.addSublayer(border)
        textField.layer.masksToBounds = true
    }
}

我在layoutSubviews()函数中编写代码作为textField的默认外观。我使用textFieldDidBeginEditing()textFieldDidEndEditing()函数来更改底部边框颜色。如果我使用代码layoutSubviews(),边框颜色根本不会被更改,但如果删除我用作默认外观的代码,边框颜色将会改变,但我没有默认边框第一次出现文本字段时。

1 个答案:

答案 0 :(得分:0)

每次开始/结束编辑文本字段时都不要创建新图层。相反,重用它:将它作为属性,然后在需要时进行相应的更新。

您可以在创建文本字段本身和边框的同一点设置的默认外观,例如:

let textField = UITextField(frame: CGRect(x: 100.0, y: 100.0, width: 200.0, height: 50.0))
let border = CALayer()

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(textField)
    textField.layer.addSublayer(border)
    textField.delegate = self

    updateBorder(textField: textField, color: UIColor.black, width: 2.0)
}

func updateBorder(textField: UITextField, color: UIColor, width: CGFloat) -> Void {
    border.backgroundColor = color.cgColor
    border.frame = CGRect(x: 0.0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: width);
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    updateBorder(textField: textField, color: UIColor.green, width: 2.0)
}

func textFieldDidEndEditing(_ textField: UITextField) {
    updateBorder(textField: textField, color: UIColor.black, width: 2.0)
}
相关问题