Swift之Delegate/閉包

Blockide

1.typealias ScenderBlock = (_ backString: String) -> Voidit

2.var block:ScenderBlock?io

3.self.block?(textField1.text!)class

4.在傳值界面import

vc.block = { backString inselect

            self.lab.text = backStringim

        }animate

 

Delegatedi

1.view

@objc protocol scenderDelegate:NSObjectProtocol{

    func backTextFieldValue(_ textString:String)

}

2.weak var delegate:scenderDelegate?

3.

if self.delegate != nil && (self.delegate?.responds(to: #selector(ScenderDelegate.backTextFieldValue(_:))))!{

            self.delegate?.backTextFieldValue(textField2.text!)

        }

4.在回傳的界面中a.添加ScenderDelegate     b. vc.delegate = self

c.

func backTextFieldValue(_ textString: String) {

        self.lab.text = textString

    }

 

所有代碼-----------------------------------------------

------------------------------------------------------

------------------------------------------------------

class ViewController: UIViewController,ScenderDelegate {

 

    @IBOutlet weak var lab: UILabel!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        

    }

 

    @IBAction func presentClick(_ sender: Any) {

        let vc:scenderVC = self.storyboard?.instantiateViewController(withIdentifier: "scenderID") as! scenderVC

        vc.block = { backString in

            self.lab.text = backString

        }

        vc.delegate = self

        self.present(vc, animated: true, completion: nil)

    }

 

    func backTextFieldValue(_ textString: String) {

        self.lab.text = textString

    }

}

 

import UIKit

 

typealias ScenderBlock = (_ backString: String) -> Void

 

@objc protocol ScenderDelegate:NSObjectProtocol{

  @objc func backTextFieldValue(_ textString:String)

}

 

class scenderVC: UIViewController {

    @IBOutlet weak var textField1: UITextField!

    @IBOutlet weak var textField2: UITextField!

    var block:ScenderBlock?

   weak var delegate:ScenderDelegate?

    

    override func viewDidLoad() {

        super.viewDidLoad()

 

 

    }

 

    

    @IBAction func blockClick(_ sender: UIButton) {

        self.block?(textField1.text!)

        self.dismiss(animated: true, completion: nil)

    }

    

    

    @IBAction func delegateClick(_ sender: Any) {

        if self.delegate != nil && (self.delegate?.responds(to: #selector(ScenderDelegate.backTextFieldValue(_:))))!{

            self.delegate?.backTextFieldValue(textField2.text!)

        }

        

        

        self.dismiss(animated: true, completion: nil)

    }

}

相關文章
相關標籤/搜索