简体   繁体   English

在Swift中的视图控制器之间传递数据

[英]Passing Data between View Controllers in Swift

I am trying to convert an app from Objective-C to Swift but I can't find how to pass data between views using Swift. 我正在尝试将应用程序从Objective-C转换为Swift,但是我找不到如何使用Swift在视图之间传递数据。 My Objective-C code is 我的Objective-C代码是

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController;
ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];

What that is doing is it basically takes the variable, theNum, and passes it to the variable, num, on a different view controller. 这样做是从根本上获取变量TheNum,并将其传递给另一个视图控制器上的变量num。 I know this may be an easy question but I am getting pretty confused with Swift so if someone could explain how they changed it to Swift that would be greatly appreciated! 我知道这可能是一个简单的问题,但是我对Swift感到非常困惑,因此,如果有人可以解释他们如何将其更改为Swift,将不胜感激!

Thanks 谢谢

Let's assumed we stand at the firstView go to the DetailView and want passing data from firstView to Detailview. 假设我们站在firstView转到DetailView,并希望将数据从firstView传递到Detailview。 To do that with storyboard, at the firstView we will have a method: 要使用情节提要进行此操作,在firstView处,我们将有一个方法:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "segueTest") {
      //Checking identifier is crucial as there might be multiple
      // segues attached to same view
      var detailVC = segue!.destinationViewController as DetailViewController;
      detailVC.toPass = textField.text
    }
}

and then into the class of DetailView we declared a variable: 然后在DetailView类中声明一个变量:

var toPass: String!

then you can use the variable toPass (of course you can change the type of the variable as you want, in this EX I just demo for string type). 那么您可以使用变量toPass (当然,您可以根据需要更改变量的类型,在此EX中,我只是演示字符串类型)。

class AnsViewController: UIViewController {
   var theNum: Int

    override func viewDidLoad() {
        super.viewDidLoad()

        println(theNum)
    }

}

override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let viewController = self.storyboard.instantiateViewControllerWithIdentifier("ansView") as AnsViewController
    viewController.num = theNum
    self.presentViewController(viewController, animated: true, completion: nil)
}

To pass string or any data from one controller to another in swift. 快速将字符串或任何数据从一个控制器传递到另一个控制器。

Follows below steps: 遵循以下步骤:

1) Create property in child controller as var abc:string! 1)在子控制器中将属性创建为var abc:string!

2) Create object of childcontroller 2)创建子控制器的对象

let storyboard:UIStoryboard()
let viewController: childcontroller = storyboard.instantiateViewControllerWithIdentifier("childcontroller") as! childcontroller
viewController.abc = "hello";
self.navigationController.pushviewController(Controller:viewController animated:true CompletionHandler:nil)
Using tableview,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
        {
            let ClubProfileView = self.storyboard?.instantiateViewController(withIdentifier: "CBClubProfileViewController") as! CBClubProfileViewController

            let TempCulubDic:NSDictionary =
                ((ClubsListbyDateDic.object(forKey:((ClubsListbyDateDic.allKeys as! [String]).sorted(by: <)as NSArray).object(at: indexPath.section) as! String) as! NSArray).object(at: indexPath.row))as! NSDictionary

            let ClubId:String=(TempCulubDic.value(forKey: "club_id") as? String)!

            let CheckIndate:String=(TempCulubDic.value(forKey: "chekin_date") as? String)!

            ClubProfileView.ClubID=ClubId

            ClubProfileView.CheckInDate = CheckIndate

            // self.tabBarController?.tabBar.isHidden=true

            ClubProfileView.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ClubProfileView, animated: true)
            }
     @IBAction func nextbtnpreesd(_ sender: Any) {

            let mystring = "2"
            performSegue(withIdentifier: "MusicVC", sender: mystring)
        }



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


        if let destination = segue.destination as? MusicVC{

            if let song = sender as? String{
                destination.strlablevalie = song
            }
        }
    }

//in MusicVC create string like: //在MusicVC中创建类似以下的字符串:

 var strlablevalie:String!

To pass string or any data from one controller to another in swift. 快速将字符串或任何数据从一个控制器传递到另一个控制器。

Follows below steps: 遵循以下步骤:

1) Create variable of type which you want like (String,Int) var test : String! 1)创建想要的类型的变量,例如(String,Int)var test:String!

2) Create object of childcontroller 2)创建子控制器的对象

 let vc = self.storyboard?.instantiateViewController(withIdentifier: "Here identifier of your VC") as! (Here Name Of Your Controller)
 vc.test = "Hello" (Or any data which you want to pass)
 self.navigationController?.pushViewController(VC, animated: true)

That should solve your problem 那应该解决你的问题

Note: if we are using storyboard 注意:如果我们使用情节提要

Step 1: Master controller : 步骤1:主控制器:

    // table row which row was selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        println("You selected cell #\(indexPath.row)!")

        nextScreenRow = indexPath.row

        // get to the next screen
        self.performSegueWithIdentifier("dashboard_static_screen_segue", sender: self)

    }

and then; 接着;

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        if (segue.identifier == "dashboard_static_screen_segue") {
            var detailController = segue.destinationViewController as StaticScreens;
            detailController.screenNumber = nextScreenRow
        }

    }// end prepareForSegue

step 2: Detail controller (StaticScreen) 步骤2:明细控制器(StaticScreen)

// set variable into your detail controller

var screenNumber: NSInteger?

println("selected row \(screenNumber!)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM