父UIView未显示,但子视图显示i nswift

父UIView未显示,但子视图显示i nswift,swift,uiview,autolayout,constraints,Swift,Uiview,Autolayout,Constraints,这是我写的代码 let topViewa = UIView() topViewa.translatesAutoresizingMaskIntoConstraints = false view.addSubview(topViewa) topViewa.backgroundColor = .white topViewa.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 300).isAc

这是我写的代码

    let topViewa = UIView()
    topViewa.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(topViewa)
    topViewa.backgroundColor = .white
    topViewa.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 300).isActive = true
    topViewa.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
    topViewa.frame.size =  CGSize(width: screenWidth, height: 44)
    let fw = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    fw.backgroundColor = .red
    topViewa.addSubview(fw)
screenWidth是屏幕的宽度

当我运行这个,这就是我得到的

为什么我没有得到白色背景的父UIView

为什么我没有得到白色背景的父UIView

因为白色视图没有大小

线路

topViewa.frame.size =  CGSize(width: screenWidth, height: 44)
…没有效果。您已选择使用约束来定位和调整此视图的大小。现在,您必须履行该合同,仅通过约束赋予其地位和规模。您没有提供任何高度或宽度约束(或者底部或尾部约束),因此视图的大小为零,而您什么也看不到


同时,红色子视图保持可见,因为白色超级视图的
clipsToBounds
false
。如果是
true
,您也不会看到红色子视图。

topViewa.frame.size=CGSize(宽度:screenWidth,高度:44)是否不足以显示尺寸?那么我需要做什么来增加尺寸?您不能使用
frame
size
。您已声明正在使用约束。必须提供高度和宽度约束,或底部和尾部约束。