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) } }
|