首页 > 解决方案 > 将 UILabel 添加到子视图后无法显示

问题描述

@IBOutlet weak var result: UILabel!

@IBOutlet weak var testview: UIView!

    override func viewDidLoad() {
   
        super.viewDidLoad()
        
        testview.layer.shadowColor = UIColor.systemGray.cgColor
        testview.layer.shadowOpacity = 0.6
        testview.layer.shadowOffset = .zero
        testview.layer.shadowRadius = 5
        
        testview.layer.shadowPath = UIBezierPath(rect: testview.bounds).cgPath
        
        testview.layer.shouldRasterize = true
        testview.layer.rasterizationScale = UIScreen.main.scale
        
        testview.addSubview(result)
    }

在我添加resulttestview子视图后,它就消失了。

标签: iosswiftxcode

解决方案


您的 Storyboard 已经添加result到视图层次结构中,因此当您再次添加它时,框架保持不变,但参考点会发生变化,因为现在超级视图是testView,所以在您的情况下,它超出了可见范围。如果您希望UILabel成为 的子视图,testView我建议直接在 Storyboard 上进行更改,以编程方式创建 UILabel 而不是使用 Storyboards/IBOutlets 或在将标签添加到testView.


推荐阅读