更改uitextfield的边框颜色

时间:2017-01-03 22:04:29

标签: ios swift uitextfield

我以这种方式向UITextField添加了底部边框:

let bottomLine = CALayer()
bottomLine.frame = CGRectMake(0.0, self.frame.height, self.frame.width, CGFloat(borderWidth))
bottomLine.backgroundColor = borderColor.CGColor
self.borderStyle = UITextBorderStyle.None
self.layer.addSublayer(bottomLine)

如何在UITextField调用textFieldDidBeginEditing()时更改此底线的边框颜色,然后在调用textFieldDidEndEditing()时将颜色更改为默认值

我正在使用自定义类UITextField

3 个答案:

答案 0 :(得分:1)

尝试在textFieldDidEndEditing方法中重新添加默认颜色的图层,如下所示:

func textFieldDidBeginEditing(_ textField: UITextField) { 
        let bottomLine = CALayer()
         bottomLine.frame = CGRectMake(0.0, self.frame.height, self.frame.width, CGFloat(borderWidth))
        bottomLine.backgroundColor = borderColor.CGColor
        self.borderStyle = UITextBorderStyle.None
        self.layer.addSublayer(bottomLine)
    }

 func textFieldDidEndEditing(_ textField: UITextField) {
    let bottomLine = CALayer()
    bottomLine.frame = CGRectMake(0.0, self.frame.height, self.frame.width, CGFloat(borderWidth))
    bottomLine.backgroundColor = defaultColor.CGColor
    self.borderStyle = UITextBorderStyle.None
    self.layer.addSublayer(bottomLine)
}

这对我有用

答案 1 :(得分:0)

textfield的操作方法设为editing did begin and editing did end

这样可以正常使用,我已经测试了它

   @IBAction func didbegin(_ sender: AnyObject) {
        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor.green.cgColor
        border.frame = CGRect(x: 0, y: txtfield.frame.size.height - width, width:  txtfield.frame.size.width, height: txtfield.frame.size.height)

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


    @IBAction func endediting(_ sender: AnyObject) {
        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor.black.cgColor
        border.frame = CGRect(x: 0, y: txtfield.frame.size.height - width, width:  txtfield.frame.size.width, height: txtfield.frame.size.height)

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

    }

希望这件事可以帮助你。

答案 2 :(得分:0)

t=# select to_char(now()::date,'Dy');
 to_char
---------
 Mon
(1 row)