【问题标题】:How to programmatically center vertically a label in Swift?如何以编程方式在 Swift 中垂直居中标签?
【发布时间】:2018-12-04 15:04:45
【问题描述】:

标签有问题。我不确定如何垂直居中这个标签:

let textRect = NSMakeRect(newX, newY , 400, 400)

let textTextContent = NSString(string: "label")
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.CenterTextAlignment

横向很容易,但纵向我找不到办法。

【问题讨论】:

  • 你在使用自动布局吗?
  • 是的。我使用自动布局。

标签: swift xcode6 osx-yosemite


【解决方案1】:

我想没有alignment 那种属性。您可以使用容器视图并将标签限制为居中。

您可以通过编程方式添加约束:

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 创建标签,很容易垂直对齐该文本,但我的标签是通过编程方式创建的
猜你喜欢
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2015-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
相关资源
最近更新 更多