So I've set up a UITextField that works correctly, but when trying to standardize the control so it can be reused in other views, I can't seem to initialize it/have it work the same way it does as a plain UITextField.
The variable is declared as
@IBOutlet weak var searchTextField: SearchTextField!
And then initialized and the delegate is set:
self.searchTextField = SearchTextField()
self.searchTextField.delegate = self
But I get EXC_BAD_INSTRUCTION when trying to set the delegate. I've been taking out and adding various init methods to the subclass, my current version has 3 which is probably overkill, but they stop the compiler from complaining:
import Foundation
class SearchTextField : UITextField
{
override init()
{
super.init()
}
override init(frame:CGRect)
{
super.init(frame:frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setPlaceholderText()
{
let searchIconCharacter: Character = "\u{1F50D}"
let searchFieldPlaceholder: String = "\(searchIconCharacter) Where to?"
self.placeholder = searchFieldPlaceholder
}
}
I'm sure my swift syntax is terrible so anything else I should correct let me know. Something is causing the SearchTextField to not be set up, it's still nil after being initialized? Is it something to do with it being a weak IBOutlet?
Since you're initializing this in code, not interface builder, change your declaration from:
@IBOutlet weak var searchTextField: SearchTextField!
to
var searchTextField = SearchTextField()
This will stop your view from getting deallocated.
Try changing
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
to
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
While there were multiple problems with my horrible code, the ultimate solution was changing the UITextField to SearchTextField in the storyboard. Aaron was also right that I was overwriting the instance created by the storyboard incorrectly, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With