首页 > 解决方案 > 父 UIView 未显示,但子视图在 nswift 中显示

问题描述

这是我写的代码

    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?

标签: swiftuiviewautolayoutconstraints

解决方案


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

因为白色视图没有大小。

线

topViewa.frame.size =  CGSize(width: screenWidth, height: 44)

……没有效果。您已选择使用约束来定位和调整该视图的大小。现在您必须履行该合同,仅通过约束为其提供位置和大小。您没有提供任何高度或宽度约束(或者,底部或尾随约束),因此视图的大小为零,您什么也看不到。

同时,红色子视图仍然可见,因为白色父视图clipsToBoundsfalse. 如果是true,您也不会看到红色子视图。


推荐阅读