如何在Swift中将值发送到父视图控制器 [英] How to send values to a parent view controller in Swift

查看:130
本文介绍了如何在Swift中将值发送到父视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用swift编写的iOS应用程序的设置视图控制器屏幕。我正在使用导航控制器来运行主设置表视图,该视图显示标题为输入方法的单元格。当前方法列在单元格的右侧。他们可以单击单元格转到下一个视图控制器,在那里他们可以选择他们喜欢的输入法。

I am working on a settings view controller screen for my iOS app written in swift. I am using a navigation controller to run the main settings table view which shows the cell titled, "Input Method." The current method is listed on the right of the cell. They can click the cell to go to the next view controller where they can select the input method that they'd like.

从这里开始,有两个部分。第一种是选择的输入法(触摸屏或操纵杆)。第二部分是关于该人是否是左撇子或右撇子的特定操纵杆。我不想让vc在选择一个盒子时放松,因为他们也可以在另一个盒子中选择一个。

From here, there are two sections. The first is the input method to choose (touchscreen or joystick). The second section is joystick specific on whether or not the person is a lefty or righty. I don't want to have the vc unwind when they choose one box because they may choose one in another section too.

我的问题:如何更新文本字段来自子控制器的父控制器。

My question: How can I update the text field in the parent controller from the child controller.

我对可选解决方案的问题:

Problems I'm having for optional solutions:

let parentVC: UIViewController = (self.navigationController?.parentViewController)!
parentVC.inputMethod.text? = cellSelected // This doesn't work because it cannot find the label inputMethod.

viewDidLoad()会导致滞后,用户在更改之前会看到旧方法。

viewDidLoad() will cause a lag and the user sees the old method before it changes.

当有人点击导航控制器左上角的后退按钮时,我找不到如何运行segue,因为导航控制器控制了segue。

I cannot find out how to run a segue when someone clicks the back button at the upper left hand side in the navigation controller, since the navigation controller controls the segue.

推荐答案

即使您确定哪个类表示,也不要强制转换父视图控制器。我将使用协议来实现:

It is not a good idea to cast the parent view controller, even when you are sure which class represents. I'll do it with a protocol:

在子控制器中添加如下协议:

In the child controller add a protocol like:

protocol ChildNameDelegate {
    func dataChanged(str: String)
}

class ChildClass {

    weak var delegate: ChildNameDelegate?

    func whereTheChangesAreMade(data: String) {
        delegate?.dataChanged(data)
    }
}

在父母中:

class ParentClass: ChildNameDelegate {

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        guard let segueId = segue.identifier else { return }

        switch segueId {
        case "childSegue":
            let destVC = segue.destinationViewController as! ChildClass
            destVC.delegate = self
            break
        default:
            break
        }
    }

    // Child Delegate
    func dataChanged(str: String) {
        // Do whatever you need with the data
    }
}

这篇关于如何在Swift中将值发送到父视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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