ioswatchkitapple-watchwkinterfacebutton

how to center title text for WKInterfaceButton with iOS WatchKit


I tried this:

[myWKButton.titleLabel setTextAlignment: NSTextAlignmentCenter];

I get the error:

property titlelabel not found on object of type wkinterfacebutton

How can I accomplish this?


Solution

  • The WKInterfaceButton class has no titleLabel property, which is the reason you are getting this error. To set the alignment of the title, use its attributedTitle property.

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:yourTitle attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];
    [myWKButton setAttributedTitle:attributedString];