我有以下代碼效果很好,但是我希望第二個文本欄位(“優先級是什么?”)是數字 1-5 的下拉選單選擇,而不是允許用戶輸入它.
// Create alert controller
let alertController = UIAlertController(title: "Add New Project", message: "Begin an empty project here.", preferredStyle: .alert)
// add textfield at index 0
alertController.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in
textField.placeholder = "Project Name"
})
// add textfield at index 1
alertController.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in
textField.placeholder = "What is the Priority (1-5)?"
})
// Alert action confirm
let confirmAction = UIAlertAction(title: "Add Project", style: .default, handler: {(_ action: UIAlertAction) -> Void in
print("action confirmed")
})
alertController.addAction(confirmAction)
// Alert action cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) -> Void in
print("Cancelled")
})
alertController.addAction(cancelAction)
// Present alert controller
present(alertController, animated: true, completion: nil)
uj5u.com熱心網友回復:
UIAlertController不支持添加選單。其公共 API 僅支持通過添加按鈕UIAlertAction和添加文本欄位。
解決這些限制的一種方法是添加一個UIButton作為文本欄位的rightView(或leftView)。使用包含 5 個可能值的 5 個操作的選單設定按鈕。
alertController.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in
textField.placeholder = "Priority"
let button = UIButton(type: .custom)
button.setTitle("Select", for: .normal)
button.menu = UIMenu(children: (1...5).map({ num in
UIAction(title: String(num)) { action in
textField.text = String(num)
}
}))
button.showsMenuAsPrimaryAction = true
textField.rightView = button
textField.rightViewMode = .always
})
文本欄位仍然是可編輯的,但用戶可以從點擊按鈕時顯示的選單中選擇一個值。
如果需要,可以使用一些技巧將文本欄位設定為只讀,同時仍然允許按鈕作業。您需要設定文本欄位delegate并false從shouldChangeCharactersIn委托方法回傳。您可以找到許多涵蓋該細節的現有問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536726.html
標籤:迅速落下警报
上一篇:按下按鈕時,修改其他按鈕
