May Phyu
May Phyu

Reputation: 905

Disable Alert Button when Text Field is Null with Swift 3

I would like to disable the alert button when the text box is null.
I put the button in Table View Cell. So, when you click that button, the alert box will pop up.
My codes are below.

  func cellTapped(cell: DeviceListTableCell) {
    self.showAlertForRow(row: tableView.indexPath(for: cell)!.row)
}

    func showAlertForRow(row: Int) {
    let alert = UIAlertController(
        title: "Enter Password !!!!!",
        message: "",
        preferredStyle: .alert)

    alert.addTextField { (textField) in

    }


    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        UIAlertAction in

        let pwd = alert.textFields?[0]

        self.password = pwd?.text

        debugPrint(self.password)
        debugPrint("Press OK")


        DispatchQueue.main.async(execute: {
            if(self.password == ""){

                debugPrint("Null Password!")
            }else{
                debugPrint("Not Null Password!")

            }
        })


    }

    alert.addAction(okAction)

    // Present the controller
    DispatchQueue.main.async(execute: {
        self.present(alert, animated: true, completion: nil)
    })

}

and

protocol ButtonCellDelegate {
func cellTapped(cell: DeviceListTableCell)}

Could anyone help me how to disable/enable the alert button?

Upvotes: 0

Views: 913

Answers (1)

Ashish
Ashish

Reputation: 726

Observe the UITextFieldTextDidChange notification to be notified when text is changed and then enable and disable okAction

// Create an alert controller
    let alertController = UIAlertController(title: "Alert", message: "Please enter text", preferredStyle: .alert)

    // Create an OK Button
    let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
      // Print "OK Tapped" to the screen when the user taps OK
      print("OK Tapped")
    }

    // Add the OK Button to the Alert Controller
    alertController.addAction(okAction)


    // Add a text field to the alert controller
    alertController.addTextField { (textField) in

      // Observe the UITextFieldTextDidChange notification to be notified in the below block when text is changed
      NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main, using:
        {_ in
          // Being in this block means that something fired the UITextFieldTextDidChange notification.

          // Access the textField object from alertController.addTextField(configurationHandler:) above and get the character count of its non whitespace characters
          let textCount = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).count ?? 0
          let textIsNotEmpty = textCount > 0

          // If the text contains non whitespace characters, enable the OK Button
          okAction.isEnabled = textIsNotEmpty

      })
    }

Upvotes: 1

Related Questions