首页 > 解决方案 > 子视图添加到视图但不显示

问题描述

我正在尝试显示已添加到视图中的子视图,但按下按钮时它不会显示。

我尝试将 isOpaque 设置为 1,将 alpha 设置为 1,将 isHidden 设置为 false(无需按下按钮)并检查我是否运行了 view.addSubview()。我还发现子视图根本没有隐藏,但背景是白色的(它应该是蓝色或红色)。

添加子视图的代码

//setup
viewBGKRect = CGRect(x: 20, y: 20, width: 984, height: 660)
viewBGK = UIView(frame: viewBGKRect)
viewBGK.backgroundColor = UIColor(red: 139.0, green: 206.0, blue: 231.0, alpha: 1.0)
viewBGK.alpha = 1
viewBGK.isOpaque = true

viewRGKRect = CGRect(x: 20, y: 20, width: 984, height: 660)
viewRGK = UIView(frame: viewRGKRect)
viewRGK.backgroundColor = UIColor(red: 240.0, green: 177.0, blue: 187.0, alpha: 1.0)
viewRGK.alpha = 1
viewRGK.isOpaque = true

//isHidden is set to false when the buttons are pressed
viewBGK.isHidden = true
viewRGK.isHidden = true

view.addSubview(viewBGK)
view.addSubview(viewRGK)

显示子视图的代码

@IBAction func goalkeeper(_ sender: UIButton) {
        switch sender.tag {
        case 0:
            // blue
            viewBGK.isHidden = false
            viewRGK.isHidden = true
            return
        default:
            viewBGK.isHidden = true
            viewRGK.isHidden = false
            return
        }
    }

我希望屏幕顶部会出现一个蓝色/红色矩形,但它没有显示。

标签: swiftaddsubview

解决方案


没关系,我找到了答案:UIColor RGB is from 0-1 not 0-255 颜色应该是

(蓝色的)

UIColor(red:0.55, green:0.81, blue:0.91, alpha:1.0)

(红色的)

UIColor(red:0.94, green:0.69, blue:0.73, alpha:1.0)

不是

(蓝色的)

UIColor(red: 139.0, green: 206.0, blue: 231.0, alpha: 1.0)

(红色的)

UIColor(red: 240.0, green: 177.0, blue: 187.0, alpha: 1.0)

我现在觉得真的很蠢。


推荐阅读