2011-09-01 57 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