2011-09-01 79 views

回答

10

UIButton不同,UITextField没有突出显示的状态。如果你想改变文本字段的颜色,当它获得焦点,您可以使用UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

当控件首次接收焦点。这将被调用。从那里你可以改变背景和/或文字颜色。一旦焦点离开控制,您可以使用

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField

来重置颜色。

+0

谢谢!很好用...... – TWcode

+3

不应该使用'textFieldDidBeginEditing'和'textFieldDidEndEditing'来代替'textFieldShouldBeginEditing'和'textFieldShouldEndEditing'吗? OP想突出显示该字段,而不是修改/检查textField是否应保持编辑模式。 – Rao

0

在斯威夫特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 
    } 
} 
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 
相关问题