简体   繁体   中英

iOS: How do I make my UITextfield highlight when tapped?

我是否必须使用代码执行此操作,或者检查器中是否存在我缺少的内容?

Unlike UIButton , a UITextField does not have a highlighted state. If you want to change the color of the textfield when it receives focus, you can use the UITextFieldDelegate 's

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

This will be called when the control first receives focus. From there you can change the background and/or text color. Once focus leaves the control, you can use

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField

to reset the colors.

In Swift 2, you can use the delegate functions like below,

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
    }
}

If you still want to be able to use other delegate functions in you ViewController, I recommend you to add this:

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)
    }
}

This way your view controller doesn't need to know that you have overwritted the delegate and you can implement UITextFieldDelegate functions in your view controller.

let yourTextField = YourTextField()
yourTextField.delegate = self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM