0%

swift3中代理和闭包的用法

swift 3 中代理和闭包(Block)的用法

其实Swift中不管是代理还是闭包,个人感觉和OC都差不多

代理,闭包:

1.新建一个类,使其继承自UIView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import UIKit
//定义一个代理
protocol MainViewDelegate {
func getTextFieldString(string:String);
}
//定义一个block
typealias GetTextFieldBlock = (_ textField:String) -> Void

class MainView: UIView {
var delegate : MainViewDelegate!
var textField : UITextField!
var textFieldBlock : GetTextFieldBlock!


func initWithFrame(frame:CGRect) -> MainView {
self.frame = frame
CreateUI()
return self
}

func CreateUI() -> Void {
let button1 = UIButton();
button1.addTarget(self, action:#selector(buttonAction1), for: UIControlEvents.touchUpInside);
button1.frame = CGRect(x:10,y:100,width:100,height:50)
button1.backgroundColor = UIColor.red
self.addSubview(button1)

textField = UITextField()
textField.frame = CGRect(x:10,y:200,width:100,height:50)
textField.backgroundColor = UIColor.white
textField.textColor = UIColor.purple
self.addSubview(textField)


let button2 = UIButton()
button2.addTarget(self, action: #selector(buttonAction2), for: .touchUpInside)
button2.frame = CGRect(x:10,y:300,width:100,height:50)
button2.backgroundColor = UIColor.darkGray
self.addSubview(button2)

}

func buttonAction1(){
delegate.getTextFieldString(string: textField.text!)//传值
}

func buttonAction2() {
if textFieldBlock != nil {
textFieldBlock(textField.text!)//传值
}
}
//该方法在外部使用
func getStringAction(_ getStringBlock:@escaping GetTextFieldBlock) {
textFieldBlock = getStringBlock
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.endEditing(true)
}
}

2.在外部调用时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import UIKit

class ViewController: UIViewController,MainViewDelegate {//遵循代理
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.orange;
createUI()
}

func createUI() {
let mainView = MainView().initWithFrame(frame: self.view.bounds)
mainView.delegate = self
self.view.addSubview(mainView)

mainView.getStringAction { (string) in
print("+++ \(string) +++")
}
}

func getTextFieldString(string: String) {
print("=== \(string) ====")
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}