对象上的 NSLayoutConstraints swift 3.0

NSLayoutConstraints on objects swift 3.0

目前我正在使用这行代码在左上角的 UILabel 上设置原点...

addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))

但是我希望原点距离左边缘 H 为 0 像素,如果有意义的话,高度的一半。

有什么建议吗?我试过更改乘数但无济于事。

我想做的是移动原点,使 (0,0) 不再是左上角,而是标签最左边和标签高度的一半,这样我就可以将标签居中正确。

首先,您必须将视图添加为其容器的子视图。完成此操作后,您需要将 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 会自动为您提供文档。如果您转到属性的参数并输入句点,您将看到所有可能选项的下拉列表。

尝试用这个设置标签的来源:

messageLabel.horizontalAlignmentMode = .Left
messageLabel.position = CGPoint(x:0.0, y:self.size.height)

无需约束!!

希望对您有所帮助:)

澄清一下,您需要标签左对齐并从上到下居中吗?

你看过NSLayoutAnchor了吗?

messageLabel = UILabel(/* Initialized somehow */)
messageLabel.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(messageLabel)
view.centerYAnchor.constraint(equalTo: messageLabel.centerYAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: messageLabel.leadingAnchor).isActive = true