天天看點

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

繼續閱讀