美文网首页
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,但是比 OC 的 block 应用面更广 在 OC 中 block 是匿名...

  • Swift学习-闭包&& 懒加载&&am

    闭包 闭包的介绍 闭包和OC中的block非常相似OC中的block是匿名的函数Swift中的闭包是一个特殊的函数...

  • iOS block和闭包

    OC中称Block swift中称闭包 其实是同一种东西 block是OC中对闭包的实现. 什么是block或者闭...

  • 14-Swift中的闭包

    闭包的介绍 闭包和OC中的Block非常相似(通俗点说:你也可以这么理解,Swift的闭包就是OC中的Block)...

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

    用法1:当作属性用 //枚举值 enum ClickType {case Login, OnlineQuote, ...

  • swift学习之闭包

    闭包的介绍 闭包和OC中的block非常相似 OC中的block是匿名的函数 Swift中的闭包是一个特殊的函数 ...

  • swift最新语法总结(闭包)

    闭包的介绍 闭包和OC中的block非常相似 OC中的block是匿名的函数 Swift中的闭包是一个特殊的函数 ...

  • Swift中的闭包简单梳理

    闭包的介绍 闭包和OC中的block非常相似 OC中的block是匿名函数 Swift中的闭包是一个特殊函数 bl...

  • Swift笔记<二十>闭包

    1.闭包的介绍 闭包和OC中的block非常相似 2.闭包的使用 block的定义属性和方法中带block 闭包=...

  • iOS&Swift&OC 闭包和Block的相互转化

    一、Swift的闭包 -> OC的block 二、OC的block -> Swift的闭包

网友评论

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

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