首页 > 解决方案 > Swift:视图隐藏按钮

问题描述

所以在情节提要中,我已经对我的视图控制器进行了查看。

此视图还具有自定义颜色,在我的代码中定义:

 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

我该如何解决?

标签: iosswiftviewstoryboardsubview

解决方案


所以检查一下。在你的方法里面

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]
}

我们看到您声明了烟雾的框架。好吧,您的烟雾变量(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 个按钮。


推荐阅读