【swift_4】swift之代理传值(delegate的用法)

前端之家收集整理的这篇文章主要介绍了【swift_4】swift之代理传值(delegate的用法)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

具体的代码,详见Demo:链接: http://pan.baidu.com/s/1gdkyWE3 密码: 4mhv


rootViewController

class ViewController: UIViewController,GetMessageDelegate
{
    var _button:UIButton?
    var _label:UILabel?

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.title = "RootViewController"
        //创建label 用来接收传过来的值
        _label = UILabel(frame: CGRect(x: 50,y: 100,width: 220,height: 44))
        _label?.text = "get message from next page"
        
        _label?.textAlignment = NSTextAlignment.Center
        _label?.backgroundColor = UIColor.cyanColor()
        self.view.addSubview(_label!)
        
        //创建button 点击跳转到下一个界面
        _button = UIButton(frame:CGRect(x:60,y:200,width:200,height:44))
        _button?.setTitle("go to next page",forState: UIControlState.Normal)
        _button?.setTitleColor(UIColor.yellowColor(),forState: UIControlState.Normal)
        _button?.backgroundColor = UIColor.blueColor()
        _button?.addTarget(self,action: "nextPage",forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(_button!)
    }

    //push
    func nextPage()
    {
        let nextVC = NextViewController()
        //指定代理
        nextVC.delegate = self
        self.navigationController!.pushViewController(nextVC,animated:true)
    }
    //接收传过来的值
    func getMessage(controller:NextViewController,string:String)
    {
        _label?.text = string
        if(string == "")
        {
            _label?.text = "null"
        }
 
    }


}

secondViewController

//创建协议
protocol GetMessageDelegate:NSObjectProtocol
{
    //回调方法 传一个String类型的值
    func getMessage(controller:NextViewController,string:String)
}
class NextViewController: UIViewController
{
    var delegate:GetMessageDelegate?
    var _textField:UITextField?
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.title = "SecondViewController"
        self.view.backgroundColor = UIColor.whiteColor()
        
        //创建textField 用来输入要传的值
        _textField = UITextField(frame: CGRect(x: 60,width: 200,height: 44))
        _textField?.borderStyle = UITextBorderStyle.RoundedRect
        _textField?.placeholder = "input sth to send back"
        self.view.addSubview(_textField!)

        //创建返回的button
        var myButton = UIButton(frame:CGRect(x:60,height:44))
        myButton.center = CGPointMake(160,200)
        myButton.setTitle("send message back",forState:.Normal)
        myButton.addTarget(self,action:"goBack",forControlEvents:.TouchUpInside)
        myButton.backgroundColor = UIColor.blueColor()
        self.view.addSubview(myButton)
    }

    func goBack()
    {
        //调用代理方法
        if((delegate) != nil)
        {
            delegate?.getMessage(self,string:_textField!.text)
            self.navigationController?.popToRootViewControllerAnimated(true)
        }
        
    }
}

猜你在找的Swift相关文章