美文网首页
swift-闭包-相当于OC中的block

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

作者: trinity_ | 来源:发表于2016-09-29 17:19 被阅读37次

    用法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

    })

    相关文章

      网友评论

          本文标题:swift-闭包-相当于OC中的block

          本文链接:https://www.haomeiwen.com/subject/dhxlyttx.html