【问题标题】:Swift: view hides buttonSwift:视图隐藏按钮
【发布时间】:2018-06-12 20:34:50
【问题描述】:

所以在情节提要中,我已经在我的视图控制器上添加了一个视图。

这个视图还有一个自定义颜色,在我的代码中定义:

 func setBlueGradientBackground(){
    let topColor = UIColor(red: 95.0/255.0, green: 165.0/255.0, blue: 1.0, alpha: 1.0).cgColor
    let bottomColor = UIColor(red: 72.0/255.0, green: 114.0/255.0, blue: 184.0/255.0, alpha: 1.0).cgColor
    smoke.frame = view.bounds
    smoke.colors = [topColor, bottomColor]

我的 viewdidload 看起来像这样:

override func viewDidLoad() {
    super.viewDidLoad()


    setBlueGradientBackground()
    lava.layer.addSublayer(smoke)
}

现在我想在我的视图上添加一个按钮。

视图以某种方式隐藏了按钮。

如果我删除了

setBlueGradientBackground() 

功能,它有效..

编辑:按钮在颜色变化的视图中。

https://imgur.com/a/9okrll6

我该如何解决这个问题?

【问题讨论】:

  • 您没有提供足够的信息。您的视图层次结构是什么样的?视图中的按钮按钮是您要更改的颜色吗?我的猜测是它在视图之下,在这种情况下它正在覆盖它。尝试使用 Xcode debug>debug view hierarchy 命令来查看视图层次结构的 3D 表示,这样你就可以知道什么在什么之上。
  • 按钮在视图内部,颜色在变化。 imgur.com/a/9okrll6

标签: ios swift view storyboard subview


【解决方案1】:

所以看看这个。在你的方法里面

func setBlueGradientBackground(){
    let topColor = UIColor(red: 95.0/255.0, green: 165.0/255.0, blue: 1.0, alpha: 1.0).cgColor
    let bottomColor = UIColor(red: 72.0/255.0, green: 114.0/255.0, blue: 184.0/255.0, alpha: 1.0).cgColor
    smoke.frame = view.bounds //HERE SEEMS TO BE CULPRIT
    smoke.colors = [topColor, bottomColor]
}

我们看到您声明了smoke 的框架。好吧,您的烟雾变量(UIView 的某些血统)似乎在您的按钮之后的某个位置添加到屏幕上。所以也许发生了这样的事情

var smoke:UILabel = UILabel()

func viewDidLoad() {
    var button = UIButton(frame: CGRect(x: self.view.frame.width*0.3, y: self.view.frame.height*0.3, width: self.view.frame.width*0.4, height: self.view.frame.height*0.4))
    self.view.addSubview(button) //ADDED BEFORE
    self.view.addSubview(smoke) //ADDED AFTER
}

现在 setBlueGradientBackground 解决这个问题的原因是因为你在那里设置了smoke's frame。因此,如果我们删除 setBlueGradientBackground,我们也不会接受烟雾的框架。烟雾现在不在屏幕上,即使它是作为视图添加的;它没有界限。因此,尽管按钮是在您的按钮之后添加的,但它无法阻止任何内容,因为它没有边界。

这是一个快速查看图层位置的小工具。在 XCode 中,当您运行程序时,在调试器工具上,您有这些按钮 -> Breakpoints、Pause、Skip、Inside、Something Else,然后您有一行看起来像这样 |。然后你有另一个按钮,看起来像 2 个矩形,1 个宽度和 1 个高度的组合,单击它,它实际上会在给定状态下暂停你的程序并显示层的位置。这很漂亮。它是图片下方的第 6 个按钮。

【讨论】:

    【解决方案2】:

    也许按钮在您的子视图后面?您是否尝试过更改视图对象的堆叠顺序?

    This post might be helpful

    【讨论】:

    • 我试过了,但编辑器中的“排列”按钮->排列是灰色的,我无法点击它
    • 不要从文档大纲(左侧窗格)中选择对象,而是尝试从构建编辑器中选择它。它应该可以工作。
    猜你喜欢
    • 2014-11-11
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2014-01-21
    • 2018-09-04
    相关资源
    最近更新 更多