首先,您必須將視圖添加爲其容器的子視圖。完成此操作後,您需要將translatesAutoResizingMaskToConstraints
設置爲false。那麼現在是時候添加你NSLayoutConstraints
:
let labelWidth:CGFloat = 320
let labelHeight:CGFloat = 30
// Container is what you are adding label too
let container = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let label = UILabel(frame: CGRect(x: 0, y: (container.frame.size.height/2) - (labelHeight/2), width: labelWidth, height: labelHeight))
container.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
// Add Width and Height (IF is required,
// if not required, anchor your label to appropriately)
label.addConstraints([
NSLayoutConstraint.init(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: labelWidth),
NSLayoutConstraint.init(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: labelHeight),
])
label.layoutIfNeeded()
// Add left constraint and center in container constraint
container.addConstraints([
NSLayoutConstraint.init(item: label, attribute: .left, relatedBy: .equal, toItem: .container, attribute: .left, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint.init(item: label, attribute: .centerX, relatedBy: .equal, toItem: .container, attribute: .left, multiplier: 1.0, constant: 0.0)
])
container.layoutIfNeeded()
編輯
是的,有當您使用點語法通過Xcode的自動給你的文檔。如果您轉到屬性的參數並輸入句點,則會看到所有可能選項的下拉列表。
我建議你修改你的代碼,以便人們可以閱讀它而不會發生荒謬的滾動。我拒絕按照原樣閱讀。 – gnasher729