ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • iOS 텍스트가 비었으면 확인 버튼 비활성하는 UIAlertController 생성
    iOS 2018. 9. 2. 09:32


    텍스트가 비었으면 확인 버튼이 비활성화되는 텍스트뷰는 자주 사용되기에 UIAlertViewController을 상속해 생성하려고 했지만,

    해당 클래스가 상속을 지원하지 않기에, 익스텐션을 활용한 형태로 생성했습니다.



    extension UIViewController {

       

        func showInputDialog(title : String? = nil, message : String? = nil,placeholder : String? = nil , defaultText : String? = nil, confirm : ((String?)->Void)? = nil  ) {

            //Creating UIAlertController and

            //Setting title and message for the alert dialog

            let alertController = UIAlertController(title:title , message: message, preferredStyle: .alert)

        

            //the confirm action taking the inputs

            let confirmAction = UIAlertAction(title: "confirm".localized, style: .default) { (_) in

                

                //getting the input values from user

                let input = alertController.textFields?[0].text

                confirm?(input)

            }

            

            //the cancel action doing nothing

            let cancelAction = UIAlertAction(title: "cancel".localized, style: .cancel) { (_) in

                

            }


            //adding the action to dialogbox

            alertController.addAction(confirmAction)

            alertController.addAction(cancelAction)

            alertController.addTextField { (textField) in

                textField.placeholder = placeholder

                textField.text = defaultText

                textField.clearButtonMode = UITextFieldViewMode.whileEditing

                textField.addTarget(alertController, action: #selector(alertController.didTextChangeInputDialog), for: UIControlEvents.editingChanged)

            }

            //finally presenting the dialog box

            DispatchQueue.main.async {

                self.present(alertController, animated: true, completion: nil)

            }

        }


    }


    extension UIAlertController {

        @objc func didTextChangeInputDialog(_ sender : UITextField){

            if (sender.text?.count == 0){

                self.actions[0].isEnabled = false

                

            }else {

                self.actions[0].isEnabled = true

            }

            

        }

    }


    내장 텍스트뷰에 타겟을 심어 알랏뷰 컨트롤러로 전송하고,

    텍스트뷰의 엠티 여부에 따라 첫번째 액션, 즉 확인 액션의 활성 여부를 변경합니다.

Designed by Tistory.