2017-06-28 141 views
0

我是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") 
} 
} 

这是什么问题?

编辑:所以我把操场放到操场上,让所有人都看到我不是疯了! enter image description here

+0

这看起来好吗......你如何将它添加为子视图? – Bilal

+0

不,只是在操场上玩...看看我的编辑。 – petaire

+0

这行:'titleLabel.topAnchor.constraint(equalTo:topAnchor,constant:20).isActive = true'等于什么的顶部锚点? 'self'? 'view'?或者是其他东西? – dfd

回答

1

您的看法有效。在操场上,你需要添加:

view.layoutIfNeeded() 

创造踢自动布局付诸行动的看法后。

+0

干得好我的朋友。 – petaire

相关问题