【问题标题】:Why does my UIButton remain after a segue?为什么我的 UIButton 在 segue 后仍然存在?
【发布时间】:2018-07-29 19:19:38
【问题描述】:

我一直在试验和练习以编程方式构建应用程序,但我无法理解为什么我的根 VC 中的 UIButton 在模态转场后仍保留在下一个视图中。当我通过情节提要执行此操作时,视图中的所有元素都会消失。

我的 rootVC 由一层和一个 UIButton 组成:

按下按钮模态显示下一个视图控制器,但 UIButton 仍然存在:

第二个 VC 文件中没有对 UIButton 的引用。下面是来自 rootVC 的代码:

var imInChinaButton : UIButton {
        var button = UIButton( frame: CGRect(
            x: 0,
            y: 0,
            width: 300,
            height: 300))
        button.setImage(#imageLiteral(resourceName: "button"), for: .normal)
        button.setTitle("hello", for: .normal)
        button.contentMode = UIViewContentMode.scaleAspectFit
        button.center = view.center
        button.backgroundColor = .clear
        button.isUserInteractionEnabled = true
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

        return button
    }

    self.view.addSubview(imInChinaButton)
}

@objc func buttonTapped(_ sender: UIButton) {
    sender.setImage(#imageLiteral(resourceName: "pressedButton"), for: .normal)
    let resultsViewController = ResultsViewController()
    self.navigationController!.present(resultsViewController, animated: true, completion: nil)
}

任何帮助都会很棒!非常感谢您的宝贵时间。

【问题讨论】:

    标签: swift uibutton


    【解决方案1】:

    你需要改变模态的背景,在viewDidLoad

    self.view.backgroundColor = .red
    

    //

    如果你不再需要 backVC ,你可以

    UIApplication.shared.keyWindow?.rootViewController =  ResultsViewController()
    

    但是暂时隐藏是不可能的,您可以这样做以在出现之前隐藏它们,但这不是一个好习惯

    self.view.subviews.forEach { $0.isHidden = true } 
    

    最好的办法是改变背景颜色或彻底清除旧的rootVC

    【讨论】:

    • 那么第二个VC?有没有最佳实践方法来做到这一点?
    • 是的,在第二个VC中,VC的背景颜色是透明的
    • 那么,如果我理解正确的话,模态segue 只是简单地将来自下一个VC 的所有视图堆叠在当前视图之上?那么有没有办法暂时“清除”rootVC?只是因为我希望背景相同,而且我不知道是否会有任何性能问题会因为多个推送/模态 segues 相互叠加......
    • 咕噜兄弟!你是传奇
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多