Swift - 传值的4种方法

2017-08-05  本文已影响20人  Simple_Code

一:代理协议

一般协议

一、在视图界面
1.制定协议
protocol DelegateName:NSObjectProtocol {
    //设置协议方法
    func method()
}
2.用weak定义代理
weak var delegate:DelegateName?

3.判断代理是否存在,让代理去执行方法
func clickButton() {
    delegate?.method()
}

二、在控制器界面
1.遵守协议
class ViewController:UIViewController,DelegateName { //遵守协议

2.设置代理为self
customView?.delegate = self

3.遵守协议方法
func method() {
    print(#function)
}

可选协议

@objc
protocol DelegateName: NSObjectProtocol
{
    @objc optional func method()
}
weak var Delegate: DelegateName?
func addBtnClick()
    {
        // !必须存在
        Delegate?. method!()
    }

添加协议DelegateName
cell.PhotoCellDelegate = self
func method() {
        
    }

二:闭包

一、 声明闭包的两种方式

1. 直接声明
var myCloure0:((Int, Int) -> Int)?

2. 定义闭包类型 (就是一个函数类型)
 typealias MyClosureType = (Int, Int) -> Int
 var myCloure:MyClosureType? 

例子:
 1. typealias InputClosureType = (String) -> Void   //定义闭包类型(特定的函数类型函数类型)
 2. var backClosure:InputClosureType?           //接收上个页面穿过来的闭包块

3. 闭包变量的Seter方法
     func setBackMyClosure(tempClosure:InputClosureType) {
         self.backClosure = tempClosure
     }
4. 调用闭包
self.backClosure!(tempString!)


二、 实现回调,接收回调过来的值
 secondVC.setBackMyClosure { (inputText:String) -> Void in
            self.showTextLabel.text = inputText
         }       

逃逸闭包

逃逸闭包一般用于异步函数的回调,比如网络请求成功的回调和失败的回调。语法:在函数的闭包行参前加关键字“@escaping”。

假设成功和失败的回调要弄成`闭包类型((Any?)->(Void))`,而你又要异步使用的话,那就要在形参前面加关键字
假设成功和失败的回调要弄成`闭包可选类型((Any?)->(Void))?`,不需在形参前面加关键字

三:通知

//注册通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "AuthSuccessNotification"), object: nil)
//监听通知
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.pageJump), name: NSNotification.Name(rawValue: "AuthSuccessNotification"), object: nil)
//销毁通知
deinit {
        NotificationCenter.default.removeObserver(self)
 }

四:NSUserDefault

//存储
UserDefaults.standard.setValue("hello", forKey: "world")
UserDefaults.standard.synchronize()
//获取
print(UserDefaults.standard.object(forKey: "world"))
上一篇下一篇

猜你喜欢

热点阅读