我在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")
}
}
答案 0 :(得分:3)
您可以尝试
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()
}
}
答案 1 :(得分:2)
要删除子视图控制器(包括其视图),您应该:
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
答案 2 :(得分:1)
您可以删除 使用
从超级视图中输入文字/视图/警报/等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()