Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Swift中以编程方式使标签垂直居中?_Swift_Xcode6_Osx Yosemite - Fatal编程技术网

如何在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创建标签,很容易垂直对齐文本,但我的标签是通过编程创建的