这是我写的代码
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?
答案 0 :(得分:1)
为什么我的父母UIView没有白色背景?
因为白色视图没有尺寸。
行
topViewa.frame.size = CGSize(width: screenWidth, height: 44)
...无效。您已选择使用约束来定位和调整该视图的大小。现在,您必须履行该合同,仅通过约束条件来赋予合同位置和规模。您没有提供任何高度或宽度限制(或者底部或尾随限制),因此视图的大小为零,您什么也看不到。
与此同时,红色子视图仍然可见,因为白色超级视图的clipsToBounds
是false
。如果它是true
,那么您也不会看到红色子视图。