swiftSwift聚焦swift

利用Swift2.0编写UIAlertController

2016-01-05  本文已影响1386人  4ba6804ff45f

下面我们仍然采用上一篇的结构来写,方便对两种语言下的编写形成对照。还是两种风格分开介绍。如果有什么没有涉及到也可以结合上一篇来看。

一、AlertView

let alertView: UIAlertController = UIAlertController.init(title: "AlertView", message: "I want to tell you something", preferredStyle: UIAlertControllerStyle.Alert)
let alertViewAction: UIAlertAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in 
      })          
let alertViewCancelAction: UIAlertAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)           
alertView.addAction(alertViewAction)
alertView.addAction(alertViewCancelAction)

效果如图:


let alertViewDestructive: UIAlertAction = UIAlertAction.init(title: "销毁", style: UIAlertActionStyle.Destructive, handler: { (UIAlertAction) -> Void in
 })
alertView.addAction(alertViewDestructive)

如图:


 alertView.addTextFieldWithConfigurationHandler({ (UITextField) -> Void in
                UITextField.placeholder = "name"
                UITextField.clearButtonMode = UITextFieldViewMode.WhileEditing
            })

效果如图:


self.presentViewController(alertView, animated:true , completion: nil)

二、ActionSheet

let alertSheet = UIAlertController.init(title: "alertSheet", message: "no message", preferredStyle: .ActionSheet)
let alertSheetAction = UIAlertAction.init(title: "确定", style: .Default, handler: nil)
alertSheet.addAction(alertSheetAction)
let alertSheetCancel = UIAlertAction.init(title: "取消", style: .Cancel, handler: nil)
alertSheet.addAction(alertSheetCancel)
let alertSheetDestructive = UIAlertAction.init(title: "销毁", style: .Destructive, handler: nil)
alertSheet.addAction(alertSheetDestructive)

效果如图:


let alertSheet = UIAlertController.init(title: nil, message: nil, preferredStyle: .ActionSheet)

效果如下:


顺便补上监听传值的那一部分

alertView.addTextFieldWithConfigurationHandler({ (UITextField) -> Void in
UITextField.placeholder = "name"
UITextField.clearButtonMode = UITextFieldViewMode.WhileEditing
                
// 设置监听
 _ = NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange:" , name: UITextFieldTextDidChangeNotification, object: UITextField)
                
})
func textChange(notification: NSNotification) {
   let textFied = notification.object as! UITextField      
   textLabel.text = textFied.text
}
deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

总结

控件的使用方法几乎是没有变化的,而且swift在语法上要简洁很多很多。使用起来也非常方便高效,如果你还在OC的坑里摸不着头脑,直接学习swift吧!

代码传送门

上一篇 下一篇

猜你喜欢

热点阅读