gpt4 book ai didi

ios - 无法设置 UIView 的背景颜色 Swift 5

转载 作者:行者123 更新时间:2023-11-28 23:21:59 26 4
gpt4 key购买 nike

我认为我是这样初始化的:

var view: UIView! = {
var perm = UIView()

perm.backgroundColor = UIColor.black

// enable auto layout
perm.translatesAutoresizingMaskIntoConstraints = false

return perm
}()

之后,我将标签作为 subview 添加到 view。标签初始化如下:

var title: UILabel! = {
let perm = UILabel()
perm.textColor = UIColor.white
perm.numberOfLines = 0
perm.font = UIFont.boldSystemFont(ofSize: 20)

// enable auto layout
perm.translatesAutoresizingMaskIntoConstraints = false

return perm
}()

之后,我以编程方式添加了一些约束。当我运行应用程序时,title 显示在正确的位置,但 view 的背景颜色尚未设置。

编辑

这是我设置约束的方式:

view.addSubview(title)

view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: image.bottomAnchor).isActive = true

title.leadingAnchor.constraint(equalTo: title.superview!.leadingAnchor, constant: 20).isActive = true
title.trailingAnchor.constraint(equalTo: title.superview!.trailingAnchor, constant: -20).isActive = true
title.bottomAnchor.constraint(equalTo: title.superview!.bottomAnchor, constant: -20).isActive = true

最佳答案

view 需要一个高度

view.heightAnchor.constraint(equalToConstant:200).isActive = true

OR 对于标签高度加上顶部和底部内边距 40

title.topAnchor.constraint(equalTo:view.topAnchor, constant:20).isActive = true

关于ios - 无法设置 UIView 的背景颜色 Swift 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59506677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com