2
votes

What I'm trying to do should be pretty straight forward from my understanding, yet I seem to be having some trouble with this.

I'm trying to add UITextField to a UITableViewCell in my Storyboard, however it only lets me place the text field as the child of a UIView, with the latter placed in the table view cell.

ie:

UITableViewCell
|__UIView
   |__UITextView

I create my IBOutlet in my Swift ViewController and add the following function to have the keyboard appear on touch

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {  
    self.nameTextField.becomeFirstResponder()  
} 

When I run this though, the cell responds to touch however it's as if the text view is always hidden and never gets enabled or becomeFirstResponder. I'm presuming it has to do with the UIView in the way, however I've been unsuccessful in placing the text view directly inside the table view cell.

If anyone has an idea on what I'm doing wrong, I'd greatly appreciate the help,

Thank you!

1

1 Answers

1
votes

Create a custom UITableView cell as a xib and make a corresponding .swift file for this. Add a textField to the cell and create an IBOutlet for the textField in the custom .swift class. Make sure your constraints are set in this xib.

In your ViewController .swift class, make the func tableView(cellForRowAtIndexPath) return your custom cell.

You do not have to set the firstResponder because the keyboard will come up by default. Unless of your cell is basically just a textField, it doesn't seem wise to have the didSelectRowAtIndexPath to always bring up the keyboard. If, for some reason that the cell always takes the touch action, then use didSelectRowAtIndexPath, but use

tableView.cellForRowAtIndexPath(indexPath).textField.becomeFirstResponder()

Set textField delegate to the custom cell and add this in the CustomTableViewCell.swift to dismiss the keyboard upon press of return key:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return false
}

Side note: The keyboard will not show in the simulator unless you deselected the option to use the hardware keyboard.

Here is a sample project with what I think you are trying to achieve: https://mega.nz/#!B1ASDIQT!8-diyv_Fd2H66nb08gs3ObzlQqVHKUUIs4U_BbI6s4s