How To Add Multiple Buttons And Editable Text Field In iOS Alert Dialog Use Swift

This article will tell you how to add one button, two buttons, three buttons, and the editable text fields in an iOS alert dialog in swift. The alert button style type can be UIAlertAction.Style.default, UIAlertAction.Style.cancel and UIAlertAction.Style.destructive. Now let us look at the demo picture below.

1. iOS Alert Dialog With Multiple Buttons & Editable Text Box Example.

There are four buttons on the screen. Press each button will prompt an alert dialog with different content.

  1. One button iOS alert dialog. The alert button style is UIAlertAction.Style.default.
    one-button-ios-alert-dialog
  2. Two buttons iOS alert dialog. The Cancel button’s style is UIAlertAction.Style.cancel, and the Ok button’s style is UIAlertAction.Style.default.
    two-buttons-ios-alert-dialog
  3. Three buttons iOS alert dialog. The Remind me later button’s style is UIAlertAction.Style.destructive.
    three-buttons-ios-alert-dialog
  4. iOS alert dialog with the input text box. One text box is a password text box. When you press the Authenticate button, it will show you whether the user account is correct or not.
    ios-alert-dialog-with-input-text-box
  5. After you press the Authenticate button in the above alert dialog, it will show another alert dialog to show you the result.
    after-authenticate-user-account-show-an-alert-dialog-with-result

2. iOS Alert Dialog With Buttons And Editable Text Box Source Code.

After creating an Xcode project with a Single View App template ( How To Create A Swift Project In Xcode ), you only need to edit the ViewController.swift file. You should copy the below source code into it.

//
//  ViewController.swift
//  iOSMultipleButtonsExample
//
//  Created by song zhao on 12/11/19.
//  Copyright © 2019 dev2qa.com. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var oneButtonAlert:UIButton? = nil
    
    var twoButtonsAlert:UIButton? = nil
    
    var threeButtonsAlert:UIButton? = nil
    
    var textFieldButtonAlert:UIButton? = nil
    
    let TAG_ONE_BUTTON_ALERT = 1
    
    let TAG_TWO_BUTTON_ALERT = 2
    
    let TAG_THREE_BUTTON_ALERT = 3
    
    let TAG_TEXT_FIELD_ALERT = 4
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initButtons()
    }

    // This function will create all the 4 buttons.
    func initButtons(){
        
        oneButtonAlert = initButton(title: "Single Button Alert", tag: TAG_ONE_BUTTON_ALERT)
        let topAnchor1 = oneButtonAlert?.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100)
        topAnchor1?.isActive = true
        
        twoButtonsAlert = initButton(title: "Two Button Alert", tag: TAG_TWO_BUTTON_ALERT)
        let topAnchor2 = twoButtonsAlert?.topAnchor.constraint(equalTo: oneButtonAlert!.bottomAnchor, constant: 50)
        topAnchor2?.isActive = true
        
        threeButtonsAlert = initButton(title: "Three Button Alert", tag: TAG_THREE_BUTTON_ALERT)
        let topAnchor3 = threeButtonsAlert?.topAnchor.constraint(equalTo: twoButtonsAlert!.bottomAnchor, constant: 50)
        topAnchor3?.isActive = true
        
        textFieldButtonAlert = initButton(title: "Text Field Alert", tag: TAG_TEXT_FIELD_ALERT)
        let topAnchor4 = textFieldButtonAlert?.topAnchor.constraint(equalTo: threeButtonsAlert!.bottomAnchor, constant: 50)
        topAnchor4?.isActive = true
        
    }

    /* This function will create one button with provided property values. */
    func initButton(title:String, tag:Int) -> UIButton{
        
        // Create a UIButton object.
        let btn:UIButton = UIButton()
        
        // Set button title.
        btn.setTitle(title, for: UIControl.State.normal)
        
        // Set this property value to false to make change button layout constraints programmatically.
        btn.translatesAutoresizingMaskIntoConstraints = false
        
        // Set button background color.
        btn.backgroundColor = UIColor.lightGray
        
        // Set button corner radius.
        btn.layer.cornerRadius = 10
        
        // Set button border width.
        btn.layer.borderWidth = 1
        
        // Set button title text break mode.
        btn.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
        
        // Set button title color.
        btn.setTitleColor(UIColor.black, for: UIControl.State.normal)
        
        self.view.addSubview(btn)
        
        // Layout this button at horizontal center.
        let btnCenterXAnchor = btn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
        btnCenterXAnchor.isActive = true
        
        // Layout this button's width as the device width minus 200.
        let btnWidthAnchor = btn.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -200)
        btnWidthAnchor.isActive = true
        
        // Set the provide tag value to this button.
        btn.tag = tag
        
        // Set button touch down event process function.
        btn.addTarget(self, action: #selector(processBtnEvent), for: UIControl.Event.touchDown)
        
        return btn
    }
    
    /* This function will process button touch down event. */
    @objc func processBtnEvent(src:UIButton, event:UIControl.Event){
                
        if(src.tag == TAG_ONE_BUTTON_ALERT)
        {
            self.showOneButtonAlert(alertTitle: "One Button Alert", alertMessage: "There is only one button in alert.", alertBtnText: "Ok", alertComplication: nil)
        }else if(src.tag == TAG_TWO_BUTTON_ALERT)
        {
            self.showTwoButtonsAlert(alertTitle: "Two Buttons Alert", alertMessage: "Do you want to continue?", alertOkBtnText: "Ok", alertCancelBtnText: "Cancel")
        }else if(src.tag == TAG_THREE_BUTTON_ALERT)
        {
            self.showThreeButtonsAlert()
        }else if(src.tag == TAG_TEXT_FIELD_ALERT)
        {
            self.showTextFieldAlert()
        }
    }
    
    // This function will show an alert dialog with one button.
    func showOneButtonAlert(alertTitle:String, alertMessage:String, alertBtnText: String, alertComplication: (() -> Void)?){
        // Create the alert controller object.
        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
        
        // Create the alert action object, the button text is OK.
        let action = UIAlertAction(title: alertBtnText, style: UIAlertAction.Style.default) { (action) in
            print("You click OK button in this one button alert.")
        }
  
        // add above action button
        alert.addAction(action)
        
        // show the alert
        present(alert, animated: true, completion: alertComplication)
    }
    
    // This function show an alert dialog with two button, one of it is UIAlertAction.Style.cancel type.
    func showTwoButtonsAlert(alertTitle:String, alertMessage:String, alertOkBtnText: String, alertCancelBtnText: String){
        
        // create the alert controller object.
        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
       
        let okAction = UIAlertAction(title: alertOkBtnText, style: UIAlertAction.Style.default) { (okAction) in
            print("You click OK button in this two buttons alert.")
        }
        
        let cancelAction = UIAlertAction(title: alertCancelBtnText, style: UIAlertAction.Style.cancel) { (cancelAction) in
            print("You click Cancel button in this two buttons alert.")
        }
        
        // add the actions (buttons)
        alert.addAction(okAction)
        alert.addAction(cancelAction)
        
        // show the alert
        present(alert, animated: true, completion: nil)
        
    }
    
    /* This function will show three buttons in an alert dialog. One is default style button, the other is cancel style button, the other is destructive style button. */
    func showThreeButtonsAlert(){
        
        // create the alert controller object.
        let alert = UIAlertController(title: "Three Buttons Alert", message: "It is time for you to eat.", preferredStyle: UIAlertController.Style.alert)
       
        let okAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (okAction) in
            print("You click OK button in this three buttons alert.")
        }
        
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { (cancelAction) in
            print("You click Cancel button in this three buttons alert.")
        }
        
        let laterAction = UIAlertAction(title: "Remind me later", style: UIAlertAction.Style.destructive) { (cancelAction) in
            print("You click Remind me later button in this three buttons alert.")
        }
        
        // add the actions (buttons)
        alert.addAction(okAction)
        alert.addAction(cancelAction)
        alert.addAction(laterAction)
        
        // show the alert
        present(alert, animated: true, completion: nil)
        
    }
    
    /* This function will display an alert dialog with input text box. */
    func showTextFieldAlert(){
        
        // Create the alert controller object.
        let alert = UIAlertController(title: "Authenticate Alert", message: "Please input your username and password to authenticate.", preferredStyle: UIAlertController.Style.alert)
        
        // Add user name text field in it.
        alert.addTextField { (userNameTextField) in
            userNameTextField.placeholder = "Please input your name"
        }
        
        // Add password text filed in it.
        alert.addTextField { (passwordTextField) in
            passwordTextField.placeholder = "Please input your password"
            
            // Set below property to make it a password input text box.
            passwordTextField.isSecureTextEntry = true
        }
        
        // This action will be used to ahthenticate username and password.
        let authAction = UIAlertAction(title: "Authenticate", style: UIAlertAction.Style.default) { (authAction) in
            
            // Get user name value.
            let userNameTextField = alert.textFields![0] as UITextField
            let userName = userNameTextField.text
            
            // Get password value.
            let passwordTextField = alert.textFields![1] as UITextField
            let password = passwordTextField.text
                        
            var msg:String = "Username and password is not correct."
            
            if((userName?.elementsEqual("hello"))! && (password?.elementsEqual("haha"))!){
                
                msg = "Username and password is correct."
            
            }
            
            print(msg)
            
            self.showOneButtonAlert(alertTitle: "Authenticate Alert", alertMessage: msg, alertBtnText: "Ok", alertComplication: nil)
    
        }
        
        alert.addAction(authAction)
        
        
        // show the alert
        present(alert, animated: true, completion: nil)
        
    }
}

References

  1. How To Prompt Alert Dialog When Click A Button In Swift

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.