【问题标题】:Removing UIView from view从视图中删除 UIView
【发布时间】:2017-07-13 09:13:16
【问题描述】:

我有一个 UIView 和一些内置在功能 menuState 中的标签和按钮。当我在 menuState 函数中单击一个按钮时,它会将我们带出该函数,进入 menuPlayButtonClicked() 函数。在这个函数中,我试图隐藏我在 menuState 函数中构建的标签和 UIView,因为游戏开始了。使用 menuView.isHidden = true 并没有这样做。 menuView.removeFromSuperView() 也没有这样做。我也尝试使用 let menuView = UIView() 全局声明这些视图和标签,但它仍然没有删除它。我错过了什么?我仍然可以在游戏组件下方的背景中看到标签和 UIView。

func menuState() {

//Build the menu box
    let menuView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 400))
    menuView.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
    self.view.addSubview(menuView)
    menuView.layer.zPosition = 1;
    menuView.layer.cornerRadius = 10
    menuView.isHidden = false

...

Also some code for a button here, which takes us to the setupGame function when clicked

}

【问题讨论】:

    标签: ios swift uiview swift3 uilabel


    【解决方案1】:

    两个函数中的“menuView”不是一个对象,只是不要使用“let”。 顺便说一句,如果以后要再次显示 menuView,请使用“isHidden”,如果您再也不会使用,请使用“removeFromSuperView”释放内存。

    【讨论】:

      【解决方案2】:

      您在全局声明的menuView 对象与在名为“menuState()”的函数中本地创建的对象不同。所以,不要声明另一个本地实例,你可以尝试以下方式 -

      menuState() {
        menuView = ...   // don't use `let` or 'var' again here, but reference the same global variable that you will use later to hide
      }
      

      【讨论】:

      • 谢谢你,做到了。就隐藏菜单选项而言,使用 .isHidden 或将其从超级视图中删除是否更有意义
      • 这需要更多的上下文来回答。但作为一个简短的答案,“isHidden”将非常适合您。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多