问题 更改自定义文本字段背景颜色和文本颜色IOS Swift


我正在使用以下自定义文本字段类来更改文本字段的外观。现在,当用户开始编辑和结束编辑文本字段时,我需要更改文本字段的背景颜色,文本颜色和占位符颜色。怎么做,使用这个类。

import Foundation
import UIKit

class CustomTextField: UITextField{

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        //Border
        self.layer.cornerRadius = 15.0;
        self.layer.borderWidth = 1.5
        self.layer.borderColor = UIColor.whiteColor().CGColor

        //Background
        self.backgroundColor = UIColor(white: 1, alpha: 0.0)

        //Text
        self.textColor = UIColor.whiteColor()
        self.textAlignment = NSTextAlignment.Center
    }

}

3948
2018-04-27 06:00


起源



答案:


根据需要将self添加为您需要的UIControl事件的目标 文件

你有EditingDidBegin等的控制事件。

像这样的东西:

self.addTarget(self, action: "myFunc", forControlEvents: UIControlEvents.EditingDidBegin);

4
2018-04-27 06:16



这种方法帮助我做我想做的事。谢谢。 - Arvin Jayanake


答案:


根据需要将self添加为您需要的UIControl事件的目标 文件

你有EditingDidBegin等的控制事件。

像这样的东西:

self.addTarget(self, action: "myFunc", forControlEvents: UIControlEvents.EditingDidBegin);

4
2018-04-27 06:16



这种方法帮助我做我想做的事。谢谢。 - Arvin Jayanake


在你的 CustomTextField 您可以添加属性观察者的类:

var change: Bool = false {
    didSet {
        textColor = change ? .yellow : .black
        backgroundColor = change ? .blue : .white
    }
}

并在您的ViewController中:

func textFieldDidBeginEditing(textField: UITextField) {
    customTextField.change = true
}

func textFieldDidEndEditing(textField: UITextField) {
    customTextField.change = false
}

不要忘记在故事板中或以编程方式设置文本字段的代理。

编辑:
缩短了代码并更新了Swift 3


10
2018-04-27 06:22



在backgroundColor线上缺少白色之前的点。它应该是:backgroundColor =改变? 。蓝白色 - crash
@crash:已编辑。谢谢 - Eendje