iOS基礎彈出框UIAlert(Swift4+Xcode9)

iOS彈出框主要由UIAlertController和UIAlertAction組成:

UIAlertController ——控制彈框顯示的內容:屬性title 和message 語義化不必多說,其中preferredStyle需注意

如果是頁面中間的彈框則是.alert

如果是頁面底部的彈框則是.actionsheet

UIAlertAction——點擊按鈕的交互行為,可以設置多個,聲明完成后需要添加到UIAlertController中

示例如下:

1.自動關閉型

效果圖:

代碼:

@IBAction func toast(){

let alertToast = UIAlertController(title: "溫馨提示", message: "恭喜您獲得一張優惠券", preferredStyle: .alert)

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

//一秒鐘后自動消失

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {

alertToast.dismiss(animated: false, completion: nil)

}


2.單按鈕手動關閉

效果圖:

代碼:

@IBAction func singleButtonAlert(){

let alert=UIAlertController(title:"溫馨提示",message:"恭喜您獲得一張優惠券",preferredStyle:.alert)

let action=UIAlertAction(title:"我知道了",style:.default,handler:nil)

alert.addAction(action)

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

}


3.多按鈕手動關閉

效果圖:

如點擊確定,會如下圖打印

雙按鈕代碼:

@IBAction func twoButtonAlert(){

let alert = UIAlertController(title:"溫馨提示",message:"恭喜您獲得一張優惠券",preferredStyle:.alert)

let cancel=UIAlertAction(title:"取消",style:.cancel)

let confirm=UIAlertAction(title:"確定",style:.default){(action)in

print("此處可以放其他操作如跳轉頁面")

}alert.addAction(cancel)

alert.addAction(confirm)

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

}

三個按鈕代碼

@IBAction func threeButtonAlert(){

let alert = UIAlertController(title:"溫馨提示",message:"恭喜您獲得一張優惠券",preferredStyle:.alert)

let cancel=UIAlertAction(title:"取消",style:.cancel)

//cancel為加粗藍色字

let confirm=UIAlertAction(title:"確定",style:.default)

//default為普通藍色字

let destructive=UIAlertAction(title:"警告",style:.destructive)

//destructive為紅色字

alert.addAction(cancel)

alert.addAction(confirm)

alert.addAction(destructive)

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

}


4.多按鈕帶輸入框手動關閉

效果圖:

代碼:

@IBAction func textFieldAlert(){

let alert = UIAlertController(title:"溫馨提示",message:"請輸入您的姓名",preferredStyle:.alert)

alert.addTextField(configurationHandler: {(textField)in

textField.placeholder="姓名"

textField.keyboardType = .default

})

let cancel=UIAlertAction(title:"取消",style:.cancel)

let confirm=UIAlertAction(title:"確定",style:.default){(action)in

print("此處可以放其他操作如跳轉頁面")

}

alert.addAction(cancel)

alert.addAction(confirm)

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

}


5.底部彈窗

效果圖:

代碼:

@IBAction func onActionSheet(){

let actionSheet=UIAlertController(title:"溫馨提示",message:"恭喜您獲得一張優惠券",preferredStyle:.actionSheet)

let cancel=UIAlertAction(title:"取消",style:.cancel)

let confirm=UIAlertAction(title:"確定",style:.default)

actionSheet.addAction(cancel)

actionSheet.addAction(confirm)

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

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容