【问题标题】:Why can't I see the constraint on this label?为什么我看不到这个标签上的约束?
【发布时间】:2017-06-28 12:04:57
【问题描述】:

我正在继承一个 UIView,我想在其中添加一个约束。但是当我这样做时,我无法添加任何约束:

class A19: UIView {
let titleLabel : UILabel = {
    let label = UILabel()
    label.text = "test"
    label.textColor = .white
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

init() {
    super.init(frame: CGRect(x: 0, y: 0, width: 414, height: 250))
    backgroundColor = .black
    addSubview(titleLabel)
    titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true
    titleLabel.sizeToFit()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

这有什么问题?

编辑:所以我把操场放在了让每个人都看到我没有疯的地方!

【问题讨论】:

  • 这看起来不错...你如何将它添加为子视图?
  • 不,只是在操场上玩……看看我的编辑。
  • 这一行:titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true 等于什么顶级锚? self? view?还是别的什么?

标签: swift uiview uilabel


【解决方案1】:

您的观点有效。在操场上,您需要添加:

view.layoutIfNeeded()

在创建视图后将 Auto Layout 付诸行动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多