Swift开发学习

swift笔记(六)--传值

2022-11-03  本文已影响0人  Harry__Li

在项目开发中,我们肯定会有传值的问题.简单学习下swift的传值

单例

单例是能在全局访问的实例.从我们第几次创建,到整个app生命周期结束时释放.
在swift中 创建如下

class PersonManger: NSObject {

    var age:NSInteger?
    static let shareinstance = PersonManger()
//    private override init(){}
}

age是单例的一个属性,当然这里也可以添加函数方法.

正向传值

把数据传递到跳转的下一个界面.

//跳转到第二个界面的时候 传递参数
func Forwardvalue(){
        
        let secVC = SecondVC.init()
        secVC.nameStr = "hello world"
        self.present(secVC, animated: true)


class SecondVC: UIViewController {

    var nameStr:String?
反向传值
protocol BackForwardDelegate {
    
    func backchuanzhi(index:NSInteger) ->Void
}
var delegate:BackForwardDelegate?

  if let testdelegate = delegate {
            testdelegate.backchuanzhi(index: 10)
        }

在第一界面当中 我们需要遵守协议
设置代理
实现协议中的方法

  /// 反向传值
    func backvalue(){
        
        let secVC = SecondVC.init()    
        //使用代理协议
        secVC.delegate = self
        
        self.present(secVC, animated: true)
    }
 func backchuanzhi(index: NSInteger) {
        print("协议传递的是:\(index)")
    }
//声明闭包
typealias FirstBackBlock = (_ index:NSInteger) -> Void

var testBlock:BackBlock?
  if testBlock != nil {
            self.testBlock!(1)
        }

而在第一个界面中

et secVC = SecondVC.init()
        
        //使用闭包
        secVC.testBlock = { [weak self] (index:NSInteger) in
            
            print("反向传递过来的参数是:\(index)")
        }
通知传值

传递参数

NotificationCenter.default.post(name: Notification.Name(rawValue: "TestNoti"), object: self, userInfo: ["key" : "123456"])

接收参数

 NotificationCenter.default.addObserver(self, selector: #selector(notibtnclick(noti:)), name: Notification.Name(rawValue: "TestNoti"), object: nil)
 @objc func notibtnclick(noti:Notification){
        
        print(noti)
        
    }
//记得移除通知
 deinit{
   NotificationCenter.default.removeObserver(self)
    }
上一篇 下一篇

猜你喜欢

热点阅读