えむじぃのアプリ開発

えむじぃのアプリ開発

元大手IT企業SE、現ベンチャー企業CTOのブログです。

【Swift】AlertにTextFieldを表示

今回はAlertにTextFieldを表示する方法をこの記事で説明します。

この記事のポイント・tag、guardを使用

AlertにTextFieldを表示する方法

AlertにTextFieldを表示する場合は以下のように設定します。

let ac = UIAlertController(title: "検索", message: "名前を入力して検索ボタンを押して下さい。", preferredStyle: .alert)
let ok = UIAlertAction(title: "検索", style: .default, handler: {[weak ac] (action) -> Void in
	guard let textFields = ac?.textFields else {
		return
	}

	guard !textFields.isEmpty else {
		return
	}

	for text in textFields {

		self.lblUid.text = text.text
		self.searchFriend()
	}
})
let cancel = UIAlertAction(title: "キャンセル", style: .cancel, handler: nil)

//TextFiledの追加
ac.addTextField(configurationHandler: {(text:UITextField!) -> Void in
	text.placeholder = "例:山田たろう"
	text.keyboardType = UIKeyboardType.alphabet
	text.tag  = 1 ← Alertに複数のTextFieldを表示する場合はtagに番号をセットして判別します。
})

ac.addAction(ok)
ac.addAction(cancel)

present(ac, animated: true, completion: nil)

これでAlertにTextFieldが表示されます。