[英]Error Calling AnimateWithDuration on a Subview from another ViewController
[英]Remove subview from another ViewController
我在HomeViewController的viewDidAppear()
中将PageViewController添加为普通视图控制器,作为子视图,如下所示:
if showTutorial == false {
addChild(controller)
controller.view.frame = view.frame
view.addSubview(controller.view)
controller.didMove(toParent: self)
}
它可以工作,但是我不知道如何再次将其删除 -PageViewController包含一个可浏览其页面的按钮。 到达某个页面,我想通过单击PageViewController内部的按钮再次从HomeViewController中删除PageViewController。
我该怎么办?
PageViewController内部的按钮:
@objc func buttonAction(sender: UIButton!) {
if currentTutorialPage != 4 {
currentTutorialPage += 1
self.setViewControllers([self.viewControllerList[currentTutorialPage]], direction: .forward, animated: false, completion: nil)
view.bringSubviewToFront(nextButton)
view.bringSubviewToFront(prevButton)
} else {
tutorialSeen = true
defaults.set(tutorialSeen, forKey: "tutorialSeen")
}
}
你可以试试
self.view.removeFromSuperview()
为了完整起见,您可以使用此扩展
@nonobjc extension UIViewController {
func add(_ child: UIViewController, frame: CGRect? = nil) {
addChild(child)
if let frame = frame {
child.view.frame = frame
}
view.addSubview(child.view)
child.didMove(toParent: self)
}
func remove() {
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
然后
@objc func buttonAction(sender: UIButton!) {
if currentTutorialPage != 4 {
currentTutorialPage += 1
self.setViewControllers([self.viewControllerList[currentTutorialPage]], direction: .forward, animated: false, completion: nil)
view.bringSubviewToFront(nextButton)
view.bringSubviewToFront(prevButton)
} else {
tutorialSeen = true
defaults.set(tutorialSeen, forKey: "tutorialSeen")
self.remove()
}
}
要删除子视图控制器(包括其视图),您应该:
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
您可以使用以下方法从超级视图中删除文本/视图/警报/等
removeFromSuperview()
例:
let loaderText = "text"
loaderText?.removeFromSuperview()
观点是一样的
let container: UIView = {
let container = UIView(frame: CGRect.zero)
container.backgroundColor = UIColor.black.withAlphaComponent(0.5)
container.translatesAutoresizingMaskIntoConstraints = false
return container
}()
这样使用
container.removeFromSuperview()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.