NSStringを中央揃え・右揃えで描画する方法

テキストを中央寄せ、右寄せで表示したい

UILabelにはtextAlignmentプロパティがあるので良いですが、NSStringから自前で文字揃えを実現する場合は少し厄介です。 NSStringの描画はdrawInRect:withAttributes:メソッドで行えますが、withAttributesに対応する文字揃え用の属性が見当たらないんですよね。

NSParagraphStyleでレイアウトを整える

NSStringの文字揃えはNSParagraphStyleを用いることで実現可能です。

NSMutableParagraphStyle *style = NSParagraphStyle.defaultParagraphStyle.mutableCopy;

/* 中央揃え */
style.alignment = NSCenterTextAlignment;
[@"Center" drawInRect:NSMakeRect(0, 0, 50, 50) withAttributes:@{NSParagraphStyleAttributeName: style}];

/* 右揃え */
style.alignment = NSRightTextAlignment;
[@"Right" drawInRect:NSMakeRect(0, 0, 50, 50) withAttributes:@{NSParagraphStyleAttributeName: style}];

広告
広告