在Swift中将变量传递回父级 [英] Passing variable back to parent in Swift

查看:74
本文介绍了在Swift中将变量传递回父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写一篇将Objective-C代码转换为swift的教程。应用程序从VC移动,其中有3个滑块(红色,绿色和蓝色)设置背景颜色,颜色名称的标签和链接到第二个VC的按钮。在第二个VC中,来自第一个VC的颜色用作背景,用户有机会命名颜色。

I am re-writing a tutorial converting the code from Objective-C to swift. The app moves from VC one where there is 3 sliders (Red, Green and Blue) that set the background colour, a label of the colour name and a button that links to the second VC. In the second VC the colour from the first VC is used as the background and the user has a chance to name the colour.

当用户输入颜色名称时,它应该将新颜色名称返回给原始VC,显示颜色名称的标签应该显示输入的文本。

When the user enters the colour name it should return the new colour name to the orginal VC and the label that shows the colour name should show the text entered.

以下是导致问题的代码:

The following is the code that is causing issue:

func textFieldShouldReturn(nameEntry: UITextField) -> Bool
{
    ViewController().colourLabel.text = nameEntry.text
    nameEntry.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    return true
}

错误致命错误:在解包时意外发现零生成一个可选值。但是调试nameEntry.text中有一个字符串。

The error "fatal error: unexpectedly found nil while unwrapping an Optional value" is generated. However debugging nameEntry.text has a string in it.

我有点难过。我可以尝试为unwind segue做准备,但它应该是一个教程应用程序。

I'm a little stumped. I could try and do a prepare for unwind segue but it is meant to be a tutorial app.

干杯

推荐答案

ViewController()实际上创建了 ViewController 的新实例。这不是对现有 ViewController 的引用。你可以做的是创建一个弱变量,指向第二个ViewController中的第一个ViewController,并将其设置为prepareForSegue或显示第二个View控制器。

ViewController() actually creates a new instance of your ViewController. This is not a reference to the already existing ViewController. What you can do is create a weak variable pointing to first ViewController inside the second ViewController and set it at prepareForSegue or when the second View controller is shown.

class SecondViewController : UIViewController {
    weak var firstViewController : ViewController?

    // Other code

    func textFieldShouldReturn(nameEntry: UITextField) -> Bool
    {
        firstViewController?.colourLabel.text = nameEntry.text
        nameEntry.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        return true
    }
}

内部第一视图控制器 prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SecondViewController" {

        let secondViewController = segue.destinationViewController as SecondViewController
        secondViewController.firstViewController = self
    }
}

这篇关于在Swift中将变量传递回父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆