Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a subclass of UITextField in swift

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?

like image 818
Tasonir Avatar asked Nov 20 '14 20:11

Tasonir


3 Answers

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.

like image 191
Aaron Brager Avatar answered Nov 18 '22 16:11

Aaron Brager


Try changing

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

to

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
like image 30
Hayley Guillou Avatar answered Nov 18 '22 18:11

Hayley Guillou


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.

like image 1
Tasonir Avatar answered Nov 18 '22 16:11

Tasonir