加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift2.0 用闭包表达式 代替 protocol 传值回调

发布时间:2020-12-14 01:44:50 所属栏目:百科 来源:网络整理
导读:在oc 中经常用到blcok 代替 prtocol 来进行回调 代码更加简洁,但是在swift 中我们通常会用 闭包表达式来进行回调传值,基础语法请百度自行补脑。 上面的博客中自定义了AlertView 用 protocol 进行了回调 代码如下 @objc protocol SwiftCustomAlertViewDeleg

在oc 中经常用到blcok 代替 prtocol 来进行回调 代码更加简洁,但是在swift 中我们通常会用 闭包表达式来进行回调传值,基础语法请百度自行补脑。
上面的博客中自定义了AlertView 用 protocol 进行了回调
代码如下

@objc protocol SwiftCustomAlertViewDelegate : NSObjectProtocol{

    optional func  selectOkButtonalertView()

    optional func  selecttCancelButtonAlertView()

}
if delegate?.respondsToSelector(Selector("selecttCancelButtonAlertView")) == true {

           print("cancelDelegate")

            delegate?.selecttCancelButtonAlertView!()
        }
if delegate?.respondsToSelector(Selector("selectOkButtonalertView")) == true {

            delegate?.selectOkButtonalertView!()
        }

下面用闭包表达式代替他们,先定义俩哥哥闭包表达式的变量

//没有回调
   var clickedCancelButtonAction:((Void)->(Void))? //回调button tag var clickedOkButtonAction:((buttonTag:NSInteger)->(Void))?
if clickedCancelButtonAction != nil {

            clickedCancelButtonAction!()

        }

     if clickedOkButtonAction != nil {

            clickedOkButtonAction!(buttonTag:button.tag)

        }

在调用的控制器里接受

let alertView = SwiftCustomAlertView(title:"swift",message:"custom swift alert",delegate: self)
        alertView .show();

        alertView.clickedCancelButtonAction = {

            print("selectCancel")
        }

        alertView.clickedOkButtonAction = {(buttonTag)->Void in

            print("Button tag (buttonTag)")
        }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读