iOS系统弹窗
2018-02-28 本文已影响0人
古月思吉
一、Alert:
- 注:UIAlertControllerStyle的alert样式在iPhone上和iPad上都能正常显示。
1.默认样式:

let alertController = UIAlertController(title: "提醒", message: "确定退出登录?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "确认", style: .default, handler: { action in
//...
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
2.自定义title、message、button样式:

在present之前加入以下代码:
//title样式
let title = NSMutableAttributedString(string: "提醒")
let titleRange = NSMakeRange(0, title.length)
title.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 17), range: titleRange)
title.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: titleRange)
alertController.setValue(title, forKey: "attributedTitle")
//message样式
let message = NSMutableAttributedString(string: "确定退出登录?")
let messageRange = NSMakeRange(0, message.length)
message.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: messageRange)
message.addAttribute(NSForegroundColorAttributeName, value: UIColor.hexColor(0x666666), range: messageRange)
alertController.setValue(message, forKey: "attributedMessage")
//button样式
cancelAction.setValue(UIColor.hexColor(0x999999), forKey: "titleTextColor")
二、ActionSheet:
1.UIAlertController实现ActionSheet:
- 注:UIAlertControllerStyle的actionSheet样式,设置方式与alert一样。但是通常只能在iPhone上正常显示;在iPad上,需要同时设置sourceView、sourceRect之后,才能正常显示,否则会闪退(sourceView:来源试图,sourceRect:来源试图的rect,actionSheet展示在sourceRect外面,箭头方向是可以改变的)。

//设置UIAlertController的样式为actionSheet
let alertController = UIAlertController(title: "提醒", message: "确定退出登录?", preferredStyle: .actionSheet)
//在iPad上,需要同时设置sourceView、sourceRect之后,才能正常显示,否则会闪退
let isPad = ( UI_USER_INTERFACE_IDIOM() == .pad)
if isPad {
alertController.popoverPresentationController!.sourceView = sender as? UIView
alertController.popoverPresentationController!.sourceRect = (sender as AnyObject).bounds
}
2.UIActionSheet实现ActionSheet:

//创建ActionSheet弹窗
let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "男","女")
actionSheet.tag = 10000
actionSheet.show(in: self.view)
//实现UIActionSheetDelegate代理
extension PersonInfoController: UIActionSheetDelegate{
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
if actionSheet.tag == 10000 {
if buttonIndex == 1 {//男
//...
} else if buttonIndex == 2 {//女
//...
}
}
}
}
- 注:代理方法 func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) 中如果在iPad上想present一个viewController,需要延迟一下才能present成功!iPhone上则可以直接present成功。
添加以下代码:
_ = delay(0.2, task: {
self.present(picker, animated: true, completion: nil)
})
- 注:
UIAlertController 是iOS8.0之后的API,UIActionSheet 是iOS8.3之后的API