【问题标题】:How do i pass information to a Uilabel in the second view controller in swift?如何快速将信息传递给第二个视图控制器中的 Uilabel?
【发布时间】:2016-06-11 21:09:32
【问题描述】:

我对 swift 还很陌生,我只是想学习不同的技术。

情况: 我有 2 个视图控制器。例如,1 号视图控制器由四个按钮(北、南、东、西)组成。假设您单击北按钮。它应该带您到 2 号视图控制器,并且视图控制器 2 中的 UiLabel 应该显示按下的任何按钮的名称(在本例中为“北”)。 我知道当你传递信息时,你应该使用“准备转场”的方法,但是有没有办法用所有 4 个按钮来做到这一点?我在 View Controller 2 中还有一个可选的字符串变量,它应该捕获从 View Controller 1 传递的信息。我到处搜索,但没有得到答案。

我目前在视图控制器 1 中的代码:

@IBAction func north(sender: UIButton) {

}
@IBAction func east(sender: UIButton) {

}
@IBAction func west(sender: UIButton) {

}
@IBAction func south(sender: UIButton) {

}

我目前在 View Controller 2 中的代码:

@IBoutlet weak var label2: UILabel!

var updateTheLabel: String?
override func viewDidLoad() {
super.viewDidLoad()
label2.text = updateTheLabel!
}

问题: 如何使用所有四个按钮执行转场以转到第二个视图控制器并分别更新 UiLabel?

【问题讨论】:

  • 你想在 ViewController 之间传递 UI 元素?

标签: ios swift


【解决方案1】:

添加到@ahmad-farrag 的解决方案

您可以修改您的 IB 操作以从按下的按钮中获取文本

var buttonText = ""

@IBAction func north(sender: UIButton) {
   buttonText = sender.currentTitle.text
}
@IBAction func east(sender: UIButton) {
   buttonText = sender.currentTitle.text
}
@IBAction func west(sender: UIButton) {
   buttonText = sender.currentTitle.text
}
@IBAction func south(sender: UIButton) {
   buttonText = sender.currentTitle.text
}

这会将按钮中的文本分配给buttonText 变量。现在在您的prepareForSegue 中,让我们假设两个视图控制器通过标识符为secondControllerSegue 的segue 连接。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if segue.identifier == "secondControllerSegue" {
      let controller = segue.destinationViewController as! SecondViewController
      controller.updateTheLabel = buttonText
   }
}

这会将我们之前捕获的buttonText 发送到secondViewController

【讨论】:

  • 谢谢!,这帮助我更了解代码:)
【解决方案2】:

是的,你可以。

只需从情节提要中删除 segues,然后以编程方式执行此操作并将您的 updateTheLabel 属性公开。

例如:

let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewControllerIdentifier") as? SecondViewController
secondViewController.updateTheLabel = "Whatever you like"

//Then push or present to the secondViewController depending on your hierarchy.
//self.navigationController?.pushViewController(secondViewController!, animated: true)
//or
//self.presentViewController(secondViewController!, animated: true, completion: nil)

【讨论】:

    【解决方案3】:

    您可以使用 NSNotificition Center 在视图控制器中

       NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.testObserver(_:)), name: "testObserver", object: ios)
    

    目标视图控制器

     func testObserver(noti : NSNotification){
        title = noti.object as? String
    }
    

    【讨论】:

    • 直接相关的控制器之间的通知是不好的编程习惯。
    • 好的。谢谢指导。请问我知道正确的原因吗?
    • 因为使用 segue,您可以免费获得对目标控制器的对象引用。通知仅在发送到多个对象或发送到与发送者完全无关的对象时才有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多