gpt4 book ai didi

ios - 为什么在呈现 View Controller 后 UIView 从层次结构中删除?

转载 作者:可可西里 更新时间:2023-11-01 02:03:49 26 4
gpt4 key购买 nike

好吧,我刚刚遇到了一些奇怪的事情。我有我的应用程序 Controller 依赖项,将 View ( header )注入(inject) View Controller 。该 View Controller 以模态方式呈现另一个 View Controller ,并且依赖项注入(inject)它自己的 header 供呈现 View Controller 使用。但是当它出现时,第一个 Controller 的标题消失了。

该属性仍处于设置状态,但已从 View 层次结构中删除。

我在新的单 View 项目中重现了这个问题:

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

self.view.backgroundColor = .white

let button = UIButton(frame: CGRect(x: 0, y: 20, width: 100, height: 50))
button.setTitle("Click Me!", for: .normal)
button.addTarget(self, action: #selector(self.segue), for: .touchUpInside)
button.backgroundColor = .black
button.setTitleColor(.lightGray, for: .normal)

self.view.addSubview(button)
}

func segue() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .lightGray

let firstVC = FirstViewController()
firstVC.sharedView = view

present(firstVC, animated: false)
}
}

class FirstViewController: UIViewController {
var sharedView: UIView!

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white

self.view.addSubview(self.sharedView)

let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50))
button.setTitle("Click Me!", for: .normal)
button.addTarget(self, action: #selector(self.segue), for: .touchUpInside)
button.backgroundColor = .black
button.setTitleColor(.lightGray, for: .normal)

self.view.addSubview(button)
}

func segue() {
let secondVC = SecondViewController()
secondVC.sharedView = self.sharedView

present(secondVC, animated: true)
}
}

class SecondViewController: UIViewController {
var sharedView: UIView!

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white

self.view.addSubview(self.sharedView)

let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50))
button.setTitle("Click Me!", for: .normal)
button.addTarget(self, action: #selector(self.segue), for: .touchUpInside)
button.backgroundColor = .black
button.setTitleColor(.lightGray, for: .normal)

self.view.addSubview(button)
}

func segue() {
self.dismiss(animated: true)
}
}

有人能解释一下这是怎么回事吗?为什么 sharedView 从 FirstViewController 中消失了?

最佳答案

-addSubview(_:) 的文档中:

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

这应该可以解释您的问题。

我建议您创建一个方法,根据您的自定义样式生成一个 headerView(每次一个新的)。

如果你真的想“复制” View ,你可以检查that answer .由于 UIView 不符合 NSCopying 标准,他们的技巧是“存档/编码”它,因为它符合 NSCoding 标准,复制 archive,并“解压/解码”它的副本。

关于ios - 为什么在呈现 View Controller 后 UIView 从层次结构中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44686469/

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