gpt4 book ai didi

iOS 新接触式 Swift 中的 Segue

转载 作者:行者123 更新时间:2023-11-30 11:27:21 25 4
gpt4 key购买 nike

我正在尝试模拟两个 View Controller 之间的 iOS 联系人。

我有一个简单的 Person 类:

class Person {
var name = ""
}

和一个包含 Person 数组的 UIViewController,该数组嵌入在 UINavigationController 中:

class PeopleViewController: UIViewController {

var people = [Person]()
var selectedPerson: Person?

switch segueIdentifier(for: segue) {
case .showPerson:
guard let vc = segue.destination as? PersonViewController else { fatalError("!") }
vc.person = selectedPerson
}

}

此 Controller 使用 Show segue 到 PersonViewController 来显示 selectedPerson:

class PersonViewController: UIViewController {
var person: Person!
}

PeopleViewController 还可以将新的 Person 添加到 Person 数组中。 NewPersonViewController模态呈现的,但是:

class NewPersonViewController: UIViewController {
var person: Person?
}

如果添加了新的 Person,我希望 NewPersonViewController 关闭,但在 View 中显示新的 Person PersonViewController 是导航堆栈的一部分。我对此的最佳猜测是:

extension NewPersonViewController {
func addNewPerson() {
weak var pvc = self.presentingViewController as! UINavigationController
if let cvc = pvc?.childViewControllers.first as? PeopleViewController {
self.dismiss(animated: false, completion: {
cvc.selectedPerson = self.person
cvc.performSegue(withIdentifier: .showPerson, sender: nil)
}
}
}
}

但是,(1)我不太高兴强制向下转换为UINavigationController,因为我期望self.presentingViewControllerPeopleViewController 类型吗? (2),闭包中是否存在内存泄漏,因为我对 pvc 使用了 weak var pvc = self.presentingViewController 但没有对于cvc?或者,最后(3)有更好的方法吗?

非常感谢您的帮助、建议等。

最佳答案

(1) I'm not too happy about forcing the downcast to UINavigationController as I would have expected self.presentingViewController to be of type PeopleViewController?

贬低并没有什么错。我肯定会取消强制展开。

(2), is there a memory leak in the closure as I've used weak var pvc = self.presentingViewController for pvc but not for cvc?

我想,没有。

(3) is there a better way of doing this?

您可以显示 NewContactVC 中新添加的联系人。当您要解雇时,请在presentingVC 上调用dismiss。

// NewPersonViewController.swift
func addNewPerson() {
// New person is added
// Show PeopleViewController modally
}

注意:以这种方式使用presentingViewController 将消除前两个/一个模态。您只会看到顶 View Controller 被解雇。如果您无法确定有多少个模态,您应该研究不同的解决方案或可能重新设计导航流程。

// PeopleViewController.swift
func dismiss() {
if let presentingVC = self.presentingViewController?.presentingViewController {
presentingVC.dismiss(animated: true, completion: nil)
} else {
self.dismiss(animated: true, completion: nil)
}
}

关于iOS 新接触式 Swift 中的 Segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50593712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com