Search code examples
ioscocoa-touchswiftuitextinputuiinputviewcontroller

Custom Input View in Swift


I've spent hours trying to figure out how to create/then get a custom inputView to work. I have a grid of TextInputs (think scrabble board) that when pressed should load a custom inputView to insert text.

I've created a .xib file containing the UI elements for the custom inputView. I was able to create a CustomInputViewController and have the inputView appear but never able to get the actual TextInput to update it's value/text.

Apple documentation has seemed light on how to get this to work and the many tutorials I've have seen have been using Obj-C (which I have been unable to convert over due to small things that seem unable to now be done in swift).

What is the overarching architecture and necessary pieces of code that should be implemented to create a customInputView for multiple textInputs (delegate chain, controller, .xibs, views etc)?


Solution

  • You shouldn't go through all that hassle. There's a new class in iOS 8 called: UIAlertController where you can add TextFields for the user to input data. You can style it as an Alert or an ActionSheet.

    Example:

    let alertAnswer = UIAlertController(title: "Input your scrabble Answer", message: nil, preferredStyle: .Alert) // or .ActionSheet
    

    Now that you have the controller, add fields to it:

    alertAnswer.addTextFieldWithConfigurationHandler { (get) -> Void in
                getAnswer.placeholder = "Answer"
                getAnswer.keyboardType = .Default
                getAnswer.clearsOnBeginEditing = true
                getAnswer.borderStyle = .RoundedRect
            } // add as many fields as you want with custom tweaks
    

    Add action buttons:

    let submitAnswer = UIAlertAction(title: "Submit", style: .Default, handler: nil)
    let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
    alertAnswer.addAction(submitAnswer)
    alertAnswer.addAction(cancel)
    

    Present the controller whenever you want with:

    self.presentViewController(alertAnswer, animated: true, completion: nil)
    

    As you see, you have various handlers to pass custom code at any step.

    As example, this is how it would look: An example of how it could look