2011-09-01 3 views

답변

10

UIButton과 달리 UITextField에는 강조 표시된 상태가 없습니다. 당신이 포커스를받을 때 텍스트 필드의 색상을 변경하려면, 당신은 사용할 수있는 UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

컨트롤이 처음 포커스를받을 때 호출됩니다. 거기에서 배경 및/또는 텍스트 색상을 변경할 수 있습니다. 포커스가 컨트롤을 벗어나면

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField

을 사용하여 색상을 재설정 할 수 있습니다.

+0

고마워요! 위대한 작품 ... – TWcode

+3

'textFieldShouldBeginEditing' 및'textFieldShouldEndEditing' 대신'textFieldDidBeginEditing' 및'textFieldDidEndEditing'을 사용해야합니까? 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 
관련 문제