luke luke - 3 months ago 20
Swift Question

how to retrieve textfield value from tableview cell

I have a tableview with 2 cells. Both cells have a textfield and a label. Textfield take the values of username/email address and password.

var emailAddress: String?
var password: String?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! TextFieldCell

cell.label.text = loginOptions[indexPath.row]
cell.textField.placeholder = loginOptions[indexPath.row]

if indexPath.row == 0 {
emailAddress = cell.textField.text!
}
if indexPath.row == 1 {
password = cell.textField.text!
}

return cell
}


Here below is a function to check whether there is any text in the textbox and if not, display an alert controller suggesting to fill in all fields.

func signInButtonTapped() {

if emailAddress!.isEmpty || password!.isEmpty {

let alert = UIAlertController(title: "Alert", message: "all fields are required to be filled in", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}

}


How do I retrieve the textfield values from inside a cell to check whether they are empty or not? The code above does not work as the textfields always return empty. Although, hopefully it can be seen what I'm trying to acheive

Answer

I guess your tableView has only one section. Then you can do this way

func signInButtonTapped() {
        let indexpathForEmail = NSIndexPath(forRow: 0, inSection: 0)
        let emailCell = tableView.cellForRowAtIndexPath(indexpathForEmail)! as TextFieldCell

        let indexpathForPass = NSIndexPath(forRow: 1, inSection: 0)
        let passCell =  tableView.cellForRowAtIndexPath(indexpathForPass)! as TextFieldCell

        if emailCell.textField.placeholder!.isEmpty || passCell.textField.placeholder!.isEmpty {

            let alert = UIAlertController(title: "Alert", message: "all fields are required to be filled in", preferredStyle: .Alert)
            let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
            alert.addAction(action)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
Comments