美文网首页
swift协议代理

swift协议代理

作者: 宁静1致远 | 来源:发表于2017-08-17 13:02 被阅读0次

    ViewController.swift

    import UIKit
    class ViewController: UIViewController,ViewController2Delegate {
        var label:UILabel?
        override func viewDidLoad() {
            super.viewDidLoad()
            label = UILabel.init(frame: CGRect(x: 20,y: 80,width: 280,height: 30))
            label?.text = "我是界面一"
            label?.textColor = UIColor.blackColor()
            self.view.addSubview(label!)
        }
        override func touchesBegan(touches: Set<</span>UITouch>, withEvent event: UIEvent?) {
            let vc2 = ViewController2.init()
            vc2.delegate = self
            self.presentViewController(vc2, animated: true, completion: nil)
        }
        //MARK-协议代理实现部分
        func click(str:NSString)->(){
            label?.text = str as String
        }
    }
    

    ViewController2.swift

    import UIKit
    @objc protocol  ViewController2Delegate{
         //optional表示可选方法,若不写,ViewController里就必须实现不然会报错
        optional func click(str:NSString)->()
    }
    class ViewController2: UIViewController {
    
        var delegate:ViewController2Delegate?
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.backgroundColor = UIColor.redColor()
        }
        override func touchesBegan(touches: Set<</span>UITouch>, withEvent event: UIEvent?) {
            self.delegate?.click!("界面二被点击了,界面一显示下")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    

    相关文章

      网友评论

          本文标题:swift协议代理

          本文链接:https://www.haomeiwen.com/subject/pjwgrxtx.html