【问题标题】:Setting background colour of view not working设置视图的背景颜色不起作用
【发布时间】:2018-06-11 14:07:48
【问题描述】:

我正在尝试以编程方式调整视图大小,使其在所有设备尺寸上看起来都不错,但我在开始时遇到了问题。

我在 main.storyboard 上设置了一个带有水平和垂直居中约束的视图。

我在viewDidLoad()方法中有如下代码:

centerView.frame.size.width = 2/3 * view.frame.width

centerView.frame.size.height = 2/3 * view.frame.height

centerView.layer.backgroundColor = UIColor.blue.cgColor

当我启动应用程序时,视图没有背景颜色。这里有什么问题?

【问题讨论】:

  • 使用:centerView.backgroundColor = .blue

标签: ios swift uiview background-color


【解决方案1】:

您将约束与框架混合在一起。您不能那样做。很可能,您的视图大小不正确,因此即使背景颜色存在,您也看不到背景颜色。检查您的视图大小在视图层次结构检查器中。

选项 1: 继续将约束与框架混合:

func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    centerView.frame.size.width = 2.0/3.0 * view.frame.width
    centerView.frame.size.height = 2.0/3.0 * view.frame.height
    centerView.layer.backgroundColor = UIColor.blue.cgColor
}

这会在布局完所有内容后设置您的视图框架。必须在viewDidLayoutSubviews 或子类的layoutSubviews 中完成。

选项 2:继续只使用约束

func viewDidLoad() {
    super.viewDidLoad()

    centerView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 2.0 / 3.0, constant: 0.0).isActive = true
    centerView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 2.0 / 3.0, constant: 0.0).isActive = true
    centerView.layer.backgroundColor = UIColor.blue.cgColor
}

选项 3: 在情节提要中执行.. 你可以乘以 2.0 / 3.0 并在此处设置背景颜色..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2019-07-07
    • 1970-01-01
    • 2013-11-18
    • 2013-06-01
    • 2014-07-20
    相关资源
    最近更新 更多