昨天的Textfield我們其實也可以改成這樣:
@IBAction func changePageAction(_ sender: Any) {
let AlertController = UIAlertController(title: "切換頁面?", message: "按下OK後跳轉", preferredStyle: .alert)
func option(optionTitle: String, optionStyle: UIAlertAction.Style ,mergehandler: ((UIAlertAction) -> Void)?) {
AlertController.addAction(UIAlertAction(title: optionTitle, style: optionStyle, handler: mergehandler))
}
option(optionTitle: "2" , optionStyle: UIAlertAction.Style.default, mergehandler: { action in
let switchToSecondScreen = SecondFrame()
self.navigationController?.pushViewController(switchToSecondScreen, animated: true)
})
option(optionTitle: "3" , optionStyle: UIAlertAction.Style.default, mergehandler: { action in
let switchToThirdScreen = ThirdFrame()
self.navigationController?.pushViewController(switchToThirdScreen, animated: true)
})
option(optionTitle: "取消" , optionStyle: UIAlertAction.Style.destructive, mergehandler: { action in
})
present(AlertController, animated: true, completion: nil)
當然我們也可以用輸入框的方式做:
@IBAction func changePageAction(_ sender: Any) {
let CancelAlertController = UIAlertController(title: "轉換頁面失敗", message: "請重試!", preferredStyle: .alert)
let AlertController = UIAlertController(title: "切換頁面?", message: "輸入你要跳轉的頁數", preferredStyle: .alert)
AlertController.addTextField { textField in
textField.placeholder = "page?"
}
let alerOktAction = UIAlertAction(title: "ok", style: .default) {[unowned AlertController] _ in
let page = AlertController.textFields?[0].text
switch page {
case "2":
let switchToSecondScreen = SecondFrame()
self.navigationController?.pushViewController(switchToSecondScreen, animated: true)
case "3" :
let switchToThirdScreen = ThirdFrame()
self.navigationController?.pushViewController(switchToThirdScreen, animated: true)
default:
self.present(CancelAlertController, animated: true, completion: nil)
}
}
let TryagainAlertAction = UIAlertAction(title: "OK", style: .destructive, handler: nil)
let alertCancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
AlertController.addAction(alerOktAction)
AlertController.addAction(alertCancelAction)
CancelAlertController.addAction(TryagainAlertAction)
present(AlertController, animated: true, completion: nil)
}
}
成果: