我是否必须使用代码执行此操作,或者检查器中是否存在我缺少的内容?
答案 0 :(得分:10)
与UIButton
不同,UITextField
没有突出显示的状态。如果要在获得焦点时更改文本字段的颜色,可以使用UITextFieldDelegate
的
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
当控件首次获得焦点时,将调用此方法。从那里你可以改变背景和/或文字颜色。一旦焦点离开控件,您可以使用
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
重置颜色。
答案 1 :(得分:0)
在Swift 2中,您可以使用下面的委托函数
class CustomTextField: UITextField, UITextFieldDelegate{
init(){
super.init(frame: CGRectMake(0, 0, 0, 0))
self.delegate = self // SETTING DELEGATE TO SELF
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.backgroundColor = UIColor.greenColor() // setting a highlight color
}
func textFieldDidEndEditing(textField: UITextField) {
textField.backgroundColor = UIColor.whiteColor() // setting a default color
}
}
答案 2 :(得分:0)
如果您仍希望能够在ViewController中使用其他委托功能,我建议您添加:
override weak var delegate: UITextFieldDelegate? {
didSet {
if delegate?.isKindOfClass(YourTextField) == false {
// Checks so YourTextField (self) doesn't set the textFieldDelegate when assigning self.delegate = self
textFieldDelegate = delegate
delegate = self
}
}
}
// This delegate will actually be your public delegate to the view controller which will be called in your overwritten functions
private weak var textFieldDelegate: UITextFieldDelegate?
class YourTextField: UITextField, UITextFieldDelegate {
init(){
super.init(frame: CGRectZero)
self.delegate = self
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.backgroundColor = UIColor.blackColor()
textFieldDelegate?.textFieldDidBeginEditing?(textField)
}
func textFieldDidEndEditing(textField: UITextField) {
textField.backgroundColor = UIColor.whiteColor()
textFieldDelegate?.textFieldDidBeginEditing?(textField)
}
}
这样你的视图控制器就不需要知道你已经覆盖了委托,你可以在视图控制器中实现UITextFieldDelegate函数。
let yourTextField = YourTextField()
yourTextField.delegate = self