iOSでユーザからのインプットを取得するためのUtil関数


概要

  • 下記のようなユーザからのインプットを取得する実装を行う
  • Closureを使って呼び出し元からシンプルに呼べるようにする

image

参考

コード

UserInputAlert.swift

  • title: ダイアログのタイトル
  • isSecure: 入力テキストをマスクするか
func userInputAlert(_ title: String, isSecure: Bool = false, callback: @escaping (String)->Void) {
    let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
    alert.addTextField(configurationHandler: {field in
        field.isSecureTextEntry = isSecure
    })
    
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        guard let text = alert.textFields?.first?.text, !text.isEmpty else {
            userInputAlert(title, callback: callback)
            return
        }
        
        callback(text)
    }))
    
//    let root = UIApplication.shared.keyWindow?.rootViewController  // Deprecated from iOS 13
    let root = UIApplication.shared.windows.first { $0.isKeyWindow }?.rootViewController
    root?.present(alert, animated: true, completion: nil)
}

呼び出し例

  • 入力されたテキストをClosureで取得する
@IBAction func buttonTapped(_ sender: Any) {
    userInputAlert("Input your message", isSecure: true) { text in
        print("DEBUG: \(text)")
    }
}