【问题标题】:parent UIView is not showing but the subviews are showing i nswift父 UIView 未显示,但子视图在 nswift 中显示
【发布时间】:2018-10-22 00:53:07
【问题描述】:

这是我写的代码

    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?

【问题讨论】:

    标签: swift uiview autolayout constraints


    【解决方案1】:

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

    因为白色视图没有大小。

    线

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

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

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

    【讨论】:

    • topViewa.frame.size = CGSize(width: screenWidth, height: 44) 是否不足以提供尺寸?那我需要怎么做才能增加尺寸呢?
    • 您不能使用framesize。您已声明您正在使用约束。您必须提供高度和宽度约束,或底部和尾随约束
    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2011-04-11
    • 2020-09-23
    • 2014-08-14
    • 1970-01-01
    • 2021-03-08
    • 2018-09-03
    相关资源
    最近更新 更多