Initializing a UITextField subclass in swift

So I set up a UITextField that works correctly, but when trying to standardize the control so that it can be reused in other views, I can't initialize / work the same as a plain UITextField.

The variable is declared as

@IBOutlet weak var searchTextField: SearchTextField!

      

And then the delegate is initialized and set:

self.searchTextField = SearchTextField()
self.searchTextField.delegate = self

      

But when I try to set the delegate, I get EXC_BAD_INSTRUCTION. I take out and subclass various init methods, my current version has 3, which is probably too large, but they prevent 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 quick syntax is terrible, so whatever I need to fix, let me know. Is there something causing the SearchTextField to not customize, is it still zero after initialization? Is it because it is a weak IBOutlet?

+3


source to share


3 answers


While there were a lot of problems with my terrible code, the end solution was to change the UITextField to SearchTextField in the storyboard. Aaron was also right that of course I was rewriting the storyboard-generated instance incorrectly.



+1


source


Since you are initializing this in code and not with an interface builder, change your declaration to:

@IBOutlet weak var searchTextField: SearchTextField!

      

to



var searchTextField = SearchTextField()

      

This will stop your performance from being released.

+3


source


Try to change

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

      

to

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

      

+1


source







All Articles