如何在Swift中以编程方式使标签垂直居中?
我对标签有问题。我不确定如何垂直居中放置此标签:如何在Swift中以编程方式使标签垂直居中?,swift,xcode6,osx-yosemite,Swift,Xcode6,Osx Yosemite,我对标签有问题。我不确定如何垂直居中放置此标签: let textRect = NSMakeRect(newX, newY , 400, 400) let textTextContent = NSString(string: "label") let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle textStyle.alignment =
let textRect = NSMakeRect(newX, newY , 400, 400)
let textTextContent = NSString(string: "label")
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.CenterTextAlignment
水平方向很容易,但垂直方向我找不到这样做的方法。我想没有对齐方式。可以使用“容器视图”并将标签约束为居中 可以通过编程方式添加约束:
containerView.addConstraints([
NSLayoutConstraint(item: containerView, attribute: .CenterX, relatedBy: .Equal, toItem: labelView, attribute: .CenterX, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: containerView, attribute: .CenterY, relatedBy: .Equal, toItem: labelView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
])
你在使用自动布局吗?是的。我使用自动布局。如果我使用IB创建标签,很容易垂直对齐文本,但我的标签是通过编程创建的