簡體   English   中英

無法設置 UIView 的背景顏色 Swift 5

[英]Can't set UIView's background color Swift 5

我有一個視圖,我像這樣初始化:

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

view需要高度

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

或對於標簽高度加上頂部和底部填充 40

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM