1.相关代码如下
iOS9.0中,苹果官方推荐使用UIAlertViewController取代之前UIAlertView,使用UIAlertView在Xcode7中会出现警告。
ViewController.swift代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button1 = UIButton()
let button2 = UIButton()
button1.frame = CGRectMake(50, 50, 100, 30)
button1.setTitle("Alert", forState: UIControlState.Normal)
button1.backgroundColor = UIColor.blackColor()
button1.addTarget(self, action: "AlertClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button1)
button2.frame = CGRectMake(50, 100, 100, 30)
button2.setTitle("ActionSheet", forState: UIControlState.Normal)
button2.backgroundColor = UIColor.blackColor()
button2.addTarget(self, action: "ActionSheetClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button2)
}
//UIAlertController和UIAlertAction的使用
func AlertClicked(sender: AnyObject){
let alertcontroller = UIAlertController(title: "Clicked", message: "我是Alert", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
let cancleAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
//将action添加到视图控制器中
alertcontroller.addAction(okAction)
alertcontroller.addAction(cancleAction)
//最后要呈现出视图控制器,否则报错error:Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior
self.presentViewController(alertcontroller, animated: true, completion: nil)
}
func ActionSheetClicked(sender: AnyObject){
let alertcontroller = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let okAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default, handler: nil)
let selectAction = UIAlertAction(title: "从手机相册选择", style: UIAlertActionStyle.Default, handler: nil)
let cancleAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
alertcontroller.addAction(okAction)
alertcontroller.addAction(selectAction)
alertcontroller.addAction(cancleAction)
//呈现出视图控制器
self.presentViewController(alertcontroller, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
2.command+R成功运行
点击Alert按钮之后,如下图:
点击ActionSheet按钮之后,如下图:(刚好看到微信修改头像是这种操作,所以做成这样)