swift 代理的使用

代理的使用方式和场景很多,这里我就用代理传值来做例子吧

首先制定协议(不写NSObjectProtocol暂时不会报错,但是写属性是无法写weak)
protocol testDeledate : NSObjectProtocol {
//设置协议方法
    func giveValue(str : String)
}

class BlockTViewController: UIViewController {
    
    var label : UITextView?
//这个地方我没使用weak来修饰好像没啥不对,区别应该还是有的我暂时没发现
    var isMydelegate : testDeledate?
    override func viewDidLoad() {
        super.viewDidLoad()
        label = UITextView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        label?.layer.borderWidth = 1
        view.addSubview(label!)
        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.green
    }

    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
//        self.present(swiftB!, animated: true, completion: nil)
        self.dismiss(animated: true, completion: nil)
//返回要传的值
        isMydelegate?.giveValue(str: "shi ni na sai")
    }

//实现代理并实现方法
class SwiftBlockViewController: UIViewController, testDeledate{
    func giveValue(str: String) {
        label?.text = str
    }
   
    var swiftT = BlockTViewController()
    var label : UITextView?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        label = UITextView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        label?.layer.borderWidth = 1
        view.addSubview(label!)
        view.backgroundColor = UIColor.yellow
//设置代理
        swiftT.isMydelegate = self
        
    }
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {        
        self.present(swiftT, animated: true, completion: nil)
    }
}

以上,就是代理传值的基本一个使用,要是有哪里不对的请各位指出!!!

你可能感兴趣的:(swift 代理的使用)