![](/img/trans.png)
[英]How do I hide UIView and make it appear when an area is tapped on screen in iOS
[英]iOS: How do I make my UITextfield highlight when tapped?
我是否必須使用代碼執行此操作,或者檢查器中是否存在我缺少的內容?
與UIButton
不同, UITextField
沒有突出顯示的狀態。 如果要在獲得焦點時更改文本字段的顏色,可以使用UITextFieldDelegate
的
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
當控件首次獲得焦點時,將調用此方法。 從那里你可以改變背景和/或文字顏色。 一旦焦點離開控件,您就可以使用
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
重置顏色。
在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
}
}
如果您仍希望能夠在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.