mohammed alwaili mohammed alwaili - 11 days ago 5
iOS Question

Change the text alignment within a label for the Apple Watch

I'd like to change the text alignment from left to center for a label in Apple Watch in code. I've searched for some answers but didn't find anything.

Answer

You can't change the properties of the label at runtime. The ugly workaround is to use attributed strings.

So in the storyboard, make the label the full width. Then for left-alignment, everything will work as usual when you set the text.

If you want centered text:

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

[self.label setAttributedText:str];
Comments