ios - 如何在 Swift 中将值发送到父 View Controller

标签 ios swift

我正在为我的 iOS 应用程序开发一个设置 View Controller 屏幕,它是用 swift 编写的。我正在使用导航 Controller 来运行主设置 TableView ,该 View 显示标题为“输入法”的单元格。当前方法列在单元格右侧。他们可以单击单元格转到下一个 View Controller ,他们可以在其中选择他们喜欢的输入法。

从这里开始,有两个部分。首先是要选择的输入法(触摸屏或操纵杆)。第二部分是操纵杆,具体说明此人是左撇子还是右撇子。我不想让 vc 在他们选择一个盒子时放松,因为他们也可能在另一部分选择一个盒子。

我的问题:如何从子 Controller 更新父 Controller 中的文本字段。

我在可选解决方案中遇到的问题:

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

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

当有人单击导航 Controller 左上角的后退按钮时,我无法找到如何运行转场,因为导航 Controller 控制转场。

最佳答案

转换父 View Controller 不是一个好主意,即使您确定代表哪个类。我会用一个协议(protocol)来做:

在子 Controller 中添加如下协议(protocol):

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

关于ios - 如何在 Swift 中将值发送到父 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439041/

相关文章:

ios - 修复github项目SwiftChart中的错误

ios - Swift函数不接受变量

ios - 输入新行时 UITextView 的偏移量错误

ios - iOS如何检测类似Airpods的蓝牙信号强度?

iphone - 使用核心图形绘制浮雕弧

ios - 如何以编程方式将我的 imageView 置于另一个 ImageView 的中心

c - Obj-C 有@available。 swift 有#available。我可以在 C/C++ 中使用什么?

ios - 键盘将显示通知。不给出键盘出现的通知

iOS 使用多个 CollectionView 重用同一个单元格

ios - 如何以编程方式检查 ios 设备的当前 userInterfaceStyle?