LoginSignup
76
70

More than 5 years have passed since last update.

UIButtonでヒラギノフォントが切れる対策(追記あり)

Last updated at Posted at 2015-07-11

追記
簡単な方法がありました。

現象

UIButtonでヒラギノフォントを使用したとき
英字の g j などが画像のように切れてしまう問題があります。

image

これはヒラギノのサイズが正確に取得できておらず、viewのframeが小さく設定されていることが問題です。

UIButtonのtitleLabelは自動で sizeToFitされてしまうため、frameの変更を行っても適応されないようです。

解決

ちょっとしたハックですが以下のようにします。

Swift

let buttonText = "abcdefghijklmnopqrstuvwxyz"
let attributes = [
    NSBaselineOffsetAttributeName: NSNumber(float:1.0)  // buttonの文字をベースラインからgの下が入るように上にずらす
]
let attrText = NSAttributedString(string: buttonText, attributes: attributes)
self.button.setAttributedTitle(attrText, forState: UIControlState.Normal)
self.button.contentEdgeInsets = UIEdgeInsetsMake(2.0, 0, 0, 0); // button内で文字を元の位置に戻す

Objective-C

NSString *buttonText = @"abcdefghijklmnopqrstuvwxyz";
NSDictionary *attributes = @{
                             NSBaselineOffsetAttributeName: [NSNumber numberWithFloat:1.0]  // buttonの文字をベースラインからgの下が入るように上にずらす
                             };
NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:buttonText attributes:attributes];
[self.button setAttributedTitle:attrText forState:UIControlStateNormal];
self.button.contentEdgeInsets = UIEdgeInsetsMake(2.0, 0, 0, 0); // button内で文字を元の位置に戻す

これで綺麗に表示されます。
image

※ 色やサイズを変更したい場合はattributesに追加する

追記 2015/07/18

いろいろ悩んでましたが、もっと簡単に解決できたのでこちらを紹介

Swift

self.button.contentVerticalAlignment = UIControlContentVerticalAlignment.Fill;

Objective-C

self.button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

これは UIButtonのSuperClassのUIControlにあるプロパティで、内部のテキストや画像をボタンのframeいっぱいに表示することができるものです。

簡単だった… orz

参考

76
70
4

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
76
70