如何在一个ViewController上设置UILabel上的文本以从另一个ViewController中提取?

时间:2017-03-27 03:37:10

标签: ios swift xcode cocoa-touch

我在UILabel上创建了一个名为order1label的{​​{1}}。

我希望根据我ThirdViewController中的决定,在该标签上显示文字。

以下是这两个视图控制器的代码。当我点击SecondViewController中的提交UIButton时,我希望SecondViewController上的orderType更改为Delivery,我希望它会反映在ThirdViewController中但是事实并非如此。它仍然说order1label

我做错了什么?我已经找了几个小时的答案,似乎没有一个简单的解决方案来解决这个非常简单的问题。

Takeout

以下是我import UIKit class SecondViewController: UIViewController{ var orderType = "Takeout" @IBAction func SubmitOrderClicked(sender: UIButton) { orderType = "Delivery" } } 的代码:

ThirdViewController

3 个答案:

答案 0 :(得分:1)

我想你在点击SecondViewController上的按钮时想要呈现ThirdViewController,所以你需要将代码更改为:

import UIKit

class SecondViewController: UIViewController{
    var orderType = "Takeout"

@IBAction func SubmitOrderClicked(sender: UIButton) {
    orderType = "Delivery"
    let thirdController = ThirdViewController()
    thirdController.order1Label.text = orderType
    self.present(thirdController, animated: true, completion: nil)
}

}

当您调用present时,您指定的视图控制器将加载并将进入viewDidLoad。您还需要删除此

var orderTextController = SecondViewController().orderType

答案 1 :(得分:1)

orderType中声明全局变量SecondViewController,如:

import UIKit

var orderType = "Takeout"

class SecondViewController: UIViewController{
@IBAction func SubmitOrderClicked(sender: UIButton) {
    orderType = "Delivery"
}

}

以下是ThirdViewController的代码:

import UIKit

class ThirdViewController: UIViewController {


override func viewWillAppear() {
    super.viewWillAppear()
    order1Label.text = orderType
}

@IBOutlet var order1Label: UILabel!

}

希望这能满足您的要求。快乐的编码。

答案 2 :(得分:0)

您的问题仅仅是因为在secondController中更改文本后需要通知thirdController中的标签。 通过单击按钮更改文本后,您需要通知thirdController中的标签也更改文本。 有几种方法可以实现,委托,通知,阻止等。 如果您对使用上述任何方式有任何疑问,请告诉我。