Внедрение UITextFieldDelegate с Swift
У меня есть класс ViewController, который реализует UITextFieldDelegate. У меня нет автоматического завершения для funcs, таких как textFieldShouldBeginEditing. Это ошибка в XCode 6? Вот моя реализация класса.
class ViewController: UIViewController, UITextFieldDelegate
Ответы
Ответ 1
Xcode 6 (Beta 1) в настоящее время не поддерживает автозаполнение для не реализованных методов/свойств протокола (для Swift).
Лучше всего использовать <CMD> - click
в протоколе, который еще не полностью реализован, чтобы увидеть, что вам не хватает.
Ответ 2
class ViewController: UIViewController,UITextFieldDelegate //set delegate to class
@IBOutlet var txtValue: UITextField //create a textfile variable
override func viewDidLoad() {
super.viewDidLoad()
txtValue.delegate = self //set delegate to textfile
}
func textFieldDidBeginEditing(textField: UITextField!) { //delegate method
}
func textFieldShouldEndEditing(textField: UITextField!) -> Bool { //delegate method
return false
}
func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
Ответ 3
Немного более осторожно...
@IBOutlet weak var nameTF: UITextField! { didSet { nameTF.delegate = self } }
Ответ 4
Swift 3.0.1
// UITextField Delegates
func textFieldDidBeginEditing(_ textField: UITextField) {
}
func textFieldDidEndEditing(_ textField: UITextField) {
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true;
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return true;
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true;
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder();
return true;
}
Ответ 5
При использовании Swift Version 3.1 с выходами UITextFields отметьте изменения.
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var txtUserID: UITextField!
@IBOutlet var txtPwd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
txtUserID.delegate = self
txtPwd.delegate = self
}
// UITextField Delegates
func textFieldDidBeginEditing(_ textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("TextField did end editing method called\(textField.text!)")
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("TextField should begin editing method called")
return true;
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("TextField should clear method called")
return true;
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
print("TextField should end editing method called")
return true;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("While entering the characters this method gets called")
return true;
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("TextField should return method called")
textField.resignFirstResponder();
return true;
}
}
Ответ 6
//MARK: - --- > Делегаты текстового поля
func textFieldDidBeginEditing(textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(textField: UITextField) {
print("TextField did end editing method called\(textField.text)")
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
print("TextField should begin editing method called")
return true;
}
func textFieldShouldClear(textField: UITextField) -> Bool {
print("TextField should clear method called")
return true;
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
print("TextField should end editing method called")
return true;
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
print("While entering the characters this method gets called")
return true;
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
print("TextField should return method called")
textField.resignFirstResponder();
return true;
}
Ответ 7
Я нашел немного работы. Просто перейдите к инспектору файла и установите тип Objective-C во время редактирования файла. Автозаполнение представляет параметры Swift.
Просто верните тип в Swift при создании.
Ответ 8
Swift 3
@IBOutlet weak var yourNameTextfield: UITextField! {
didSet {
yourNameTextfield.delegate = self
}
}
extension YourNameViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
}
func textFieldDidEndEditing(_ textField: UITextField) {
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder();
return true
}
}
Ответ 9
В моем случае по ошибке я добавил методы делегата вне области реализации класса в swift и ограничивает методы делегата для вызова.
Ответ 10
Я ошибочно воспользовался точкой с запятой, добавив в оператор жестов, который отвечал за вызов view.endEditing(true), который в свою очередь вызывает методы делегата, такие как textFieldShouldBeginEditing. Интересный swift не показывает время компиляции или ошибки времени выполнения для точек с запятой, добавленных иногда, после удаления точки с запятой все просто отлично работает.