swift-闭包-相当于OC中的block

2016-09-29  本文已影响37人  trinity_

用法1:当作属性用


//枚举值

enum ClickType {

case Login, OnlineQuote, ProductIntroduction, MyTask, Phone

}

//定义闭包

typealias clickButtonsFuction = (_ clickType:ClickType)->Void

var clickButton : clickButtonsFuction?

@IBAction func clickLoginButton(_ sender: AnyObject) {

if clickButton != nil {

clickButton!(ClickType.login)

}

}

//在外界使用时

let headView = Bundle.main.loadNibNamed("HomeHeadView", owner: nil, options: nil)?.last as? HomeHeadView

headView!.clickButton = {

(clickType: ClickType)->Void in

switch clickType {

case ClickType.login:

self.presentToLogin()//登录

default:break

}

用法2:直接当做参数传给外界


//简单封装一个alert

class var current : LAlert {

struct Private {

static let instance = LAlert()

}

return Private.instance

}

//定义变量

typealias clickAlertButtonFunction = (_ index:Int)->Void

var clickAlertButtonsBlock : clickAlertButtonFunction?

//封装alert

func showAlertInViewController(viewController:UIViewController, title:String?, message:String, buttons:Array, clickButtonBlock:@escaping clickAlertButtonFunction)->Void{

let alertController : UIAlertController = UIAlertController.init(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

clickAlertButtonsBlock = clickButtonBlock

for index in 0..<buttons.count {

let action : UIAlertAction = UIAlertAction.init(title: buttons[index], style: UIAlertActionStyle.default, handler: { (action) in

if self.clickAlertButtonsBlock != nil {

self.clickAlertButtonsBlock!(index)

}

alertController.dismiss(animated: true, completion: nil)

})

alertController.addAction(action)

}

viewController.present(alertController, animated: true, completion: nil)

}

//应用场景

LAlert.current.showAlertInViewController(viewController: self, title: "错误提示 ", message: "手机号码不正确", buttons: ["知道了"], clickButtonBlock: { (index) in

})

上一篇 下一篇

猜你喜欢

热点阅读