Swift 正向傳值以及利用閉包(closure)實現反向傳值(七)
阿新 • • 發佈:2019-02-13
// MainVc
let button = UIButton.init(type: UIButtonType.Custom)
button.frame = CGRectMake(20, 100, 50, 50);
button.backgroundColor = UIColor.cyanColor()
self.view.addSubview(button)
button.addTarget(self, action: Selector("click:"), forControlEvents: UIControlEvents.TouchUpInside)
textField = UITextField.init (frame: CGRectMake(20, 160, 100, 50));
self.view.addSubview(textField)
textField.placeholder = "I am Placehoder"
func addressThatTakesAClosure(string:String) ->Void{
textField.text = string
}
func click(sender: UIButton)
{
// 初始化
let sec = MainViewController()
// 類似於屬性傳值
sec.string = "Success"
/***********************************************/
// ---------------華麗的分割線---------------- //
// 用函式把地址傳過去, 用於回撥
// sec.initWithClosure(addressThatTakesAClosure)
// 或者直接這樣
sec.myClosure = addressThatTakesAClosure
self.navigationController?.pushViewController(sec, animated: true )
}
// SecVc
// 類似於OC中的typedef
typealias sendValueClosure = (string:String)->Void
var string = ""
// 宣告一個Closure(閉包)
var myClosure:sendValueClosure?
// 下面這個方法需要傳入上個介面的addressThatTakesAClosure函式指標
func initWithClosure(closure:sendValueClosure?){
myClosure = closure
}
// 類似於OC中的屬性傳值
print("Success: \(string)")
let label = UILabel.init(frame: CGRectMake(10, 100, 150, 30))
label.text = string
self.view.addSubview(label)
func backButtonCreate()
{
// 返回按鈕
var buttonRight = UIButton()
buttonRight = UIButton.init(type: UIButtonType.Custom)
buttonRight.backgroundColor = UIColor.redColor()
buttonRight.frame = CGRectMake(280, 100, 50, 50)
self.view.addSubview(buttonRight)
buttonRight.setTitle("返回", forState: UIControlState.Normal)
buttonRight.addTarget(self, action: Selector("click"), forControlEvents: UIControlEvents.TouchUpInside)
}
// 返回點選方法
func click()
{
if myClosure != nil{
myClosure!(string: string);
} self.navigationController?.popToRootViewControllerAnimated(true)
}