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

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

})

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 自从iOS9出来之后,需要使用UIAlertController来弹出弹框,不在提倡使用UIAlertView了,...
    南京杨小兵阅读 574评论 1 0
  • iOS 8的新特性之一就是让接口更有适应性、更灵活,因此许多视图控制器的实现方式发生了巨大的变化。全新的UIPre...
    Tank丶Farmer阅读 2,118评论 2 4
  • { 11、核心动画 需要签协议,但是系统帮签好 一、CABasicAnimation 1、创建基础动画对象 CAB...
    CYC666阅读 1,589评论 2 4
  • 转自星夜暮晨的博客 对话框样式 1`创建Alert控制器 Objective-C版本: UIAlertContro...
    哇次哟累阅读 1,293评论 0 0
  • 接受不完美的自己,接受他人的指责,接受内心深处的表达,从另一个角度去看
    Blackguy阅读 134评论 0 0