关闭

iOS项目开发实战(Swift)—View之间传递数据

2113人阅读 评论(4) 收藏 举报
分类:

1.ViewController.swift

import UIKit

class ViewController: UIViewController {
    let textField = UITextField()
    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.frame = CGRectMake(20, 20, 100, 50)
        textField.textColor = UIColor.blueColor()
        textField.placeholder = "Input:"
        
        button.frame = CGRectMake(0, 55, 50, 50)
        button.backgroundColor = UIColor.blackColor()
        button.setTitle("UP", forState: UIControlState.Normal)
        button.addTarget(self, action: "jump", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
        self.view.addSubview(textField)
    }
    
    func jump(){
        let viewController = NextViewController()
        //传递数据
        viewController.labelContent = textField.text!
        presentViewController(viewController, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


2.NextViewController.swift

import UIKit

class NextViewController: UIViewController {

    var label = UILabel()
    var labelContent = " "
    var button = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        label.frame = CGRectMake(20, 20, 100, 50)
        label.textColor = UIColor.blackColor()
        label.text = labelContent
        self.view.addSubview(label)
        
        button.frame = CGRectMake(20, 80, 50, 50)
        button.setTitle("Back", forState: UIControlState.Normal)
        button.backgroundColor = UIColor.blackColor()
        button.addTarget(self, action: "backPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func backPressed(sender: AnyObject){
        //返回上一个视图
        dismissViewControllerAnimated(true, completion: nil)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


3.总结(成功运行结果如下图)

在View1中输入Beijing,然后点击UP按钮跳转到第二个View,可以看到Beijing已经传递过来,然后可以点击Back返回第一个View。


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:260079次
    • 积分:3867
    • 等级:
    • 排名:第8526名
    • 原创:147篇
    • 转载:13篇
    • 译文:0篇
    • 评论:59条
    博客专栏
    LeetCode

    文章:48篇

    阅读:23427
    关于我
    最新评论