swift基础学习传值[属性传值、代理、block代码块、等]

前端之家收集整理的这篇文章主要介绍了swift基础学习传值[属性传值、代理、block代码块、等]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

传值:在此之前我们先定义两个视图控制器ViewController ViewController01

1.属性传值正向、这里以字符串做例子、其他类型类似:ViewController->>>ViewController01


ViewController:

let vc = ViewController01()

vc.str ="hello"

self.navigationController?.pushViewController(vc,animated:true)


ViewController01:

class ViewController01: UIViewController {

var str =NSString()

overridefunc viewDidLoad() {

super.viewDidLoad()

self.view.backgroundColor =UIColor.white

print(self.str)

}

overridefunc didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

2.代码块反向传值

ViewController:

func click() {

let vc =ViewController01()

vc.callBlock{(value: String?) ->Void in

print(value)

}

self.navigationController?.pushViewController(vc,animated:true)

}

ViewController01:

首先定义代码块类型:typealias textBlock = (String)->()

然后定义代码属性:var block:textBlock?

实现代码

func callBlock(block:textBlock?) {

self.block = block

}

func click() {

if let block = self.block {

block("li01")

}

self.navigationController?.popToRootViewController(animated:true)

}


3.delegate反向传值(协议)

ViewController:首先要继承ViewController01中的协议giveFirstStrDelegate

func click() {

let vc =ViewController01()

vc.delegate = self

self.navigationController?.pushViewController(vc,animated:true)

}

代理方法

func giveStr(controller: ViewController01,string: String) {

print(string)

}

ViewController01:

首先定义个协议

protocol giveFirstStrDelegate:NSObjectProtocol {

func giveStr(controller:ViewController01,string:String)

}

var delegate:giveFirstStrDelegate?

这些类似与OC中的代理实现

func click() {

if((delegate) !=nil){

delegate?.giveStr(controller:self,string:"hi I am li")

}

self.navigationController?.popToRootViewController(animated:true)

}

4.通知中心传值参考OC

5.单列传值也同样参考OC

基本是写过OCswift都可以很容易上手

原文链接:https://www.f2er.com/swift/322946.html

猜你在找的Swift相关文章