Reputation: 5
I am very new to Swift programming and am trying to understand why i can't make a custom UIView class also act as the delegate for TextFields. I have converted code that works with ViewController, but without much luck. The error is: fatal error: unexpectedly found nil while unwrapping an Optional value which is generated by the line : textField.delegate = self
Code as below:
import UIKit
class ViewClass: UIView, UITextFieldDelegate {
var textItems = [UITextInput]()
var myKB = UIToolbar()
var txtActive = 0
@IBOutlet weak var textField: UITextField!
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
textField.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")
}
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 snd 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;
}
}
Is this just impossible or am I missing/misunderstanding something basic??
Upvotes: 0
Views: 2710
Reputation: 131408
Short answer: You can make a view a text field's delegate, but you should not do that.
View objects display data. Controller objects implement the logic of your app. You shouldn't store model data in your view objects, nor should they have logic in them.
As to HOW to do it:
Outlets are not connected in init. For view controllers, the place where you can assume your outlets are wired up is viewDidLoad. For view objects, the place where you can assume that everything is connected is the awakeFromNib()
method. You should implement awakeFromNib()
and set up your delegate there.
Upvotes: 2
Reputation: 4583
this is not an issue with UITextFieldDelegate but with how you setup textfield. You are telling the class that textField is an IBOutlet that will definitely be connected by this line of code
@IBOutlet weak var textField: UITextField!
However, when it tries to access textField in the init method, it throws a compiler error that says that there is nothing in textField.
So textField's IBOutlet probably needs to be connected to something in the associated Storyboard
Upvotes: 0