NSLayoutConstraints 3.0

问题描述:

目前我使用这行代码上设置在左上角一个UILabel原点...NSLayoutConstraints 3.0

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

但是我想的起源是从左边0像素H和一半的高度,如果这是有道理的。

有什么建议吗?我试图改变乘数无济于事。

我想要做的是移动原点,使得(0,0)不是左上角,而是标签的最左侧和标签高度的一半,以便我可以正确地将标签居中。

+1

我建议你修改你的代码,以便人们可以阅读它而不会发生荒谬的滚动。我拒绝按照原样阅读。 – gnasher729

只是为了澄清,你需要的标签左对齐,并居中从上到下?您是否看过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 

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

enter image description here

+0

你指的是哪个常量?如果您的意思是标签的宽度和高度,我将其设置在代码的最顶端。 –

+0

有没有在我可以看到NSLayoutConstraints的所有可能的属性的文档中的任何地方? – Stefan

+0

@Stefan我更新了我的答案 –

尝试设置您的标签的来源与此:

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

没有必要的约束!

希望有所帮助你:)

+0

如果您的应用程序被锁定旋转,那么对于约束**没有* need *。这意味着您的应用只有一个*方向设置,横向或纵向。如果你想允许你的应用程序中的方向改变,你真的需要使用自动布局。唯一的其他选择是听取系统中的方向更改并手动调整UI元素的位置。这是非常乏味的,在自动布局转换过程中不够优雅,而且在iOS开发的今天,不使用自动布局是一个重大错误。 –

+0

由于不需要乘数或常数,所以不需要约束。斯蒂芬只是想设置按钮顶部让角落就是它 – chetan

+0

没有适当的限制标签框架将保持不变的方向改变。是的,你可以添加它,但最初的问题是关于NSLayoutConstraint。 –