码迷,mamicode.com
首页 > 编程语言 > 详细

Swift语言实现代理传值

时间:2015-02-14 09:51:27      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

需求:利用代理实现反响传值(下面样例採用点击第二个视图控制器中的button来改变第一个视图控制器中的Label的内容)

一、创建RootViewController

import Foundation
import UIKit

class RootViewController:UIViewController,ChangeWordDelegate{
    var qzLabel:UILabel?
    override func viewDidLoad(){
        super.viewDidLoad()
        self.title = "RootViewController"
        let rightBtn:UIBarButtonItem = UIBarButtonItem(title:"下一页",style:.Plain,target:self,action:"nextPage")
        self.navigationItem.rightBarButtonItem = rightBtn
        
        let rect = CGRect(x:0,y:200,width:320,height:50)
        qzLabel = UILabel(frame:rect)
        qzLabel!.text = "秦志伟"
        qzLabel!.textAlignment = NSTextAlignment.Center
        self.view.addSubview(qzLabel)
        
        
    }
    func nextPage(){
        let svc = SecondViewController()
        svc.delegate = self
        self.navigationController.pushViewController(svc,animated:true)
    }
    func changeWord(controller:SecondViewController,string:String){
        qzLabel!.text = string
        println("qzLabel.text == \(string)")
    }
}


二、创建SecondViewController

import Foundation
import UIKit

//定义协议改变Label内容
protocol ChangeWordDelegate:NSObjectProtocol{
    //回调方法
    func changeWord(controller:SecondViewController,string:String)
}
class SecondViewController:UIViewController{
    var temp = 0
    var delegate:ChangeWordDelegate?
    override func viewDidLoad(){
        super.viewDidLoad()
        self.title = "SecondViewController"
        self.view.backgroundColor = UIColor.greenColor()
        let rect = CGRect(x:50,y:200,width:150,height:50)
        var myButton = UIButton(frame:rect)
        myButton.center = CGPointMake(160,200)
        myButton.setTitle("改变Label内容",forState:.Normal)
        myButton.addTarget(self,action:"btnClicked",forControlEvents:.TouchUpInside)
        self.view.addSubview(myButton)
        
    }
    func btnClicked(){
        temp++
        println("我被点击了!")
        if(delegate){
            delegate?.changeWord(self,string:"秦志伟"+String(temp))
        }
        
    }
}


Swift语言实现代理传值

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4291248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!