Swift实现传值的四种方法

常用的四种传值方法:单例,代理,闭包,通知(一)

(例如:从页面a,反向传值(这里是背景颜色backgroundColor)到页面b)

1.单例

1>.创建单例变量 在AppDelegate.swift 中创建变量var backgroundColor:UIColor?

2>在页面a中创建单例对象:

func changeBlue(){

        let appDele = UIApplication.sharedApplication().delegate as! AppDelegate

        appDele.backgroundColor = UIColor.blueColor()

        self.dismissViewControllerAnimated(true, completion: nil)

}

3>在页面b中重写父类方法,并调用单例的变量完成数值的传递

override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)

        let appDele = UIApplication.sharedApplication().delegate as! AppDelegate

        self.view.backgroundColor = appDele.backgroundColor

}



2.代理

/*扩展一下代理的使用步骤:

 代理和协议的使用

 A.delegate = B

 3     2      1

 

 A:

1)确定谁是A           

2)A.delegate = **** 

3)A.delegate调用代理方法

 

delegate:

1)定义一个协议和对应的方法

2)声明delegate的属性

 

B:

1)B(firstCtrl)遵守协议,实现代理方法

 */

1)确定谁是A:这里是页面a

2)A.delegate = **** 

func clickBtn(){

        let secondCtrl = SecondViewController()

        //设置代理

        secondCtrl.delegate = self

        self.presentViewController(secondCtrl, animated: true, completion: nil)

}

3)A.delegate 调用代理方法

func backAction(){

        //调用代理属性的方法

        self.delegate?.sendValue((self.label?.text)!)

        self.dismissViewControllerAnimated(true, completion: nil)

}

1)定义一个协议和对应的方法

protocol SecondViewControllerDelegate {

    func sendValue(text: String)

}


2)声明delegate的属性

//代理属性

    var delegate: SecondViewControllerDelegate?

1)B(firstCtrl) 遵守协议,实现代理方法

class FirstViewController: UIViewController, SecondViewControllerDelegate {}

//MARK: SecondViewController的代理

extension FirstViewController{

        func sendValue(text: String) {

        self.label?.text = text

    }

}





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值