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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24222640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:54:04  来源:igfitidea点击:

Passing Data between View Controllers in Swift

iosswiftuistoryboarduistoryboardsegue

提问by lagoon

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. My Objective-C code is

我正在尝试将应用程序从 Objective-C 转换为 Swift,但我找不到如何使用 Swift 在视图之间传递数据。我的 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. 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!

它所做的基本上是获取变量 theNum,并将其传递给不同视图控制器上的变量 num。我知道这可能是一个简单的问题,但我对 Swift 感到非常困惑,所以如果有人能解释他们如何将其更改为 Swift,将不胜感激!

Thanks

谢谢

回答by lee

Let's assumed we stand at the firstViewgo to the DetailViewand want passing data from firstView to Detailview. To do that with storyboard, at the firstView we will have a method:

让我们假设我们站在firstView转到DetailView并希望将数据从 firstView 传递到 Detailview。要使用 storyboard 做到这一点,在 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 DetailViewwe 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 中我只是演示字符串类型)。

回答by fulvio

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)
}

回答by Rizwan Shaikh

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)

回答by Dipesh Khandhar

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)
            }

回答by Paresh Hirpara

     @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!

回答by Paresh Hirpara

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

那应该可以解决您的问题

回答by Vinod Joshi

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!)")