更改 Apple Watch 标签内的文本对齐方式

Change the text alignment within a label for the Apple Watch

我想在代码中将 Apple Watch 中标签的文本对齐方式从左更改为居中。我搜索了一些答案,但没有找到任何答案。

您无法在运行时更改标签的属性。丑陋的解决方法是使用属性字符串。

所以在情节提要中,将标签设置为全宽。然后对于左对齐,当您设置文本时一切都会照常进行。

如果您希望文本居中:

NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setAlignment:NSTextAlignmentCenter];
NSAttributedString *str = [[NSAttributedString alloc]
  initWithString:@"Hello" attributes:@{NSParagraphStyleAttributeName: paraStyle}];

[self.label setAttributedText:str];

在Swift-3中可以通过以下方式执行:

func changeAttributeOfText() {
        let paragraphStyle =  NSMutableParagraphStyle()
        paragraphStyle.alignment = .left
        let font = UIFont.boldSystemFont(ofSize: 12)
        let attributes:Dictionary = [NSParagraphStyleAttributeName:paragraphStyle ,  NSFontAttributeName:font ]
        let attributeString:NSAttributedString = NSAttributedString(string: "HELLO", attributes: attributes)
        textLabel.setAttributedText(attributeString)
    }

Demo App