swift协议代理

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语言开发中使用协议+代理的用法和oc中是一样的,只不过变得是语法。现在就进入swift的协议+代理。 先...
    符武阅读 7,514评论 2 7
  • 转载自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子阅读 12,880评论 0 36
  • 我出生在湖北的一个小城市,小的时候最大的愿望,就是能够出去看看外面的世界。上大学的时候来到武汉,读的是我梦想中的大...
    张清楚阅读 1,709评论 0 1
  • 要在自己一个人的时候学会走长长的路 要在冷的时候叮嘱自己多穿衣 要在寂寞的时候抱紧自己睡觉,尽管睡姿像只猫咪 要在...
    丹筠颜阅读 1,319评论 0 1
  • 你站在那里。那里就是一道风景。 ——6.25
    文森古堡阅读 1,170评论 0 1