[英]iOS: How do I make my UITextfield highlight when tapped?
我是否必须使用代码执行此操作,或者检查器中是否存在我缺少的内容?
Unlike UIButton
, a UITextField
does not have a highlighted state. 与
UIButton
不同, UITextField
没有突出显示的状态。 If you want to change the color of the textfield when it receives focus, you can use the UITextFieldDelegate
's 如果要在获得焦点时更改文本字段的颜色,可以使用
UITextFieldDelegate
的
- (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, 在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
}
}
If you still want to be able to use other delegate functions in you ViewController, I recommend you to add this: 如果您仍希望能够在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)
}
}
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. 这样,您的视图控制器不需要知道您已经覆盖了委托,您可以在视图控制器中实现UITextFieldDelegate函数。
let yourTextField = YourTextField()
yourTextField.delegate = self
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.