LoginSignup
36
36

More than 5 years have passed since last update.

NSAttributeTextを使って、テキストの英数字と日本語のフォントを別々に適用して完成度をアップ!

Last updated at Posted at 2014-03-06

アプリではフォントの選択も重要な要素になるため、デフォルト以外のフォントの活用も非常に行うと思います。

ただし、適応したいフォントによっては、英字の場合と日本語のテイストがいまいちしっくりこないことが多々あるかと思います。
そこでNSAttributeを使って、一部だけ別のフォントを当ててみることにします。
たとえば,UILabelにそのような処理を組み込みたい場合、


-(void)updateAttributeText{
    if(self.text == nil){
        return;
    }

    NSError *error;
    // スタイルを引き継ぎ・
    NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStylealloc] init];
    paragrapStyle.alignment = self.textAlignment;
    paragrapStyle.lineBreakMode = self.lineBreakMode;


    NSDictionary *attr = @{
                           NSStrokeColorAttributeName :self.textColor, NSFontAttributeName:[UIFontsystemFontOfSize:self.font.pointSize],NSParagraphStyleAttributeName:paragrapStyle};


    NSMutableAttributedString *attrStr = [[NSMutableAttributedStringalloc] initWithString:self.textattributes:attr];


    // 正規表現で英数字を抜き出す。
    NSRegularExpression *regexp = [NSRegularExpressionregularExpressionWithPattern:@"([a-zA-Z0-9]+)"options:0error:&error];
    if (error == nil) {
        NSArray *arr = [regexp matchesInString:attrStr.string options:0 range:NSMakeRange(0, attrStr.length)];
        for (NSTextCheckingResult *match in arr) {
            //別のフォントを適用
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont fontWithName:@"Arial Rounded MT Bold" size:self.font.pointSize]
                            range:[match rangeAtIndex:1]];
        }
    }
    // attributedtextを設定
    self.attributedText = attrStr;


}

と行った処理であとは適宜このメソッドを呼べば、個別にフォントを出し分けた形で表示することが可能です。

細かなところまでの調整でアプリの完成度が違ってくるため、こだわってアプリを作り込みましょう!

36
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
36