问题
I'm following the Big Nerd Ranch iOS Programming book (Swift version) and I have this file.
import UIKit
class ConversionViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var celsiusLabel: UILabel!
@IBOutlet var textField: UITextField!
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
print("here")
return true
}
//rest of the code here
}
For some reason, the textField delegate method is not called. I can't see the "here" log in my console. I have double checked the naming and syntax a lot of times. Any ideas?
回答1:
You need set delegate of your text field to self.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
回答2:
Is this line present?
textField.delegate = self
回答3:
I was missing a _
in my function, after the first parenthesis:
This doesn't work:
func textFieldDidBeginEditing(textField: UITextField) {
}
This works:
func textFieldDidBeginEditing(_textField: UITextField) {
}
回答4:
you have to follow these step --
1- put delegate
with class name .
class YourViewController: UIViewController,UITextFieldDelegate
2- assign the delegate
in viewDidLoad
method.
textField.delegate = self
3- add the delegate
method --
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
// return NO to disallow editing.
return true
}
func textFieldDidBeginEditing(_ textField: UITextField)
{
// became first responder
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool
{
// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
return true
}
func textFieldDidEndEditing(_ textField: UITextField)
{
// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason)
{
// if implemented, called in place of textFieldDidEndEditing:
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
// return NO to not change text
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool
{
// called when clear button pressed. return NO to ignore (no notifications)
return true
}
回答5:
For this function:
func textFieldDidBeginEditing(_textField: UITextField) { }
make sure you don't mark it as private. e.g. don't to this:
private func textFieldDidBeginEditing(_textField: UITextField) { }
It won't get called if marked private.
来源:https://stackoverflow.com/questions/34842153/uitextfielddelegate-method-not-called