无法设置UIView的背景色Swift 5

时间:2019-12-27 22:41:07

标签: ios swift uiview nslayoutconstraint

我有这样的初始化看法:

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

    perm.backgroundColor = UIColor.black

    // enable auto layout
    perm.translatesAutoresizingMaskIntoConstraints = false

    return perm
}()

之后,我将标签添加为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

1 个答案:

答案 0 :(得分:1)

s需要高度

view

或为标签高度加上顶部和底部填充40

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