天天看点

Swift基础之Delegate方法的使用

本文简单介绍了使用Delegate方法的进行值的传递,改变上一个界面的字体大小和颜色

首先创建一个导航视图:

let viewC = ViewController();

        let navigationC = UINavigationController.init(rootViewController: viewC);

        window?.rootViewController = navigationC;

在ViewController视图中创建跳转按钮和显示字体的UILabel

override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        self.title = "首页"

        self.view.backgroundColor = UIColor.lightGrayColor();

        //添加按钮

        let buttonN = UIButton.init(frame: CGRectMake(100, 80, 150, 50));

        buttonN.setTitle("进入下一层", forState: .Normal);

        buttonN.setTitleColor(UIColor.blueColor(), forState: .Normal);

        buttonN.addTarget(self, action: #selector(buttonNClick), forControlEvents: .TouchUpInside);

        self.view.addSubview(buttonN);

        //显示字体

        nameLabel = UILabel.init(frame: CGRectMake(50, 200, 200, 50));

        nameLabel.text = "111111111";

        nameLabel.font = UIFont.systemFontOfSize(20);

        nameLabel.textColor = UIColor.redColor();

        nameLabel.layer.borderWidth = 1;

        self.view.addSubview(nameLabel);

    }

    //按钮的点击方法

    func buttonNClick(btn:UIButton) {

        let oneVC = OneViewController();

        //从前往后传值,这里跟OC中的在 .h 文件中利用@property进行描述的变量类似效果

        oneVC.nameStr = "你好,明天";

        //设置协议delegate

        oneVC.delegateFont = self;

        self.navigationController?.pushViewController(oneVC, animated: true);

    }

    //实现代理的方法

    func fontSizeDidChange(controllerR: OneViewController, fontSize: Int, fontColor: UIColor) {

        nameLabel.font = UIFont.systemFontOfSize(CGFloat(fontSize));

        nameLabel.textColor = fontColor;

    }

在OneViewController文件中创建代理方法,并在上一个界面实现方法:

//定义代理对象

    var delegateFont:FontSizeChangeDelegate?;//定义一个协议,实现可以从前往后传值

protocol FontSizeChangeDelegate:NSObjectProtocol{

    //定义一个delegate函数

    //参数1:代理创建时所在的Controller,参数2:字体大小,参数3:字体颜色

    func fontSizeDidChange(controllerR:OneViewController ,fontSize:Int,fontColor:UIColor);

    //可以添加更多的协议方法......

}

//定义代理对象

    var delegateFont:FontSizeChangeDelegate?;

//使用代理方法

        if (delegateFont != nil) {

            //调用协议方法

            delegateFont?.fontSizeDidChange(self, fontSize: fontSize, fontColor: colorR)

        }

效果显示:

Swift基础之Delegate方法的使用
Swift基础之Delegate方法的使用
Swift基础之Delegate方法的使用

注意:上面是部分代码显示,详细使用请下载Demo:http://download.csdn.net/detail/hbblzjy/9597865

继续阅读