アプリ開発の逆引き辞典

アプリ開発のTipsをまとめました

NSStringクラスのdrawInRect:withFont:lineBreakMode:alignment:メソッドをワーニングが出ないように書き換える

NSStringクラスのdrawInRect:withFont:lineBreakMode:alignment:メソッドは、iOS 7.0から「deprecated(非推奨)」となり、下図のようなワーニング表示されるようになりました。

f:id:ch3cooh393:20140327181840p:plain

横に長いため全文表示ができていませんが、下記のようなワーニングが表示されています。

'drawInRect:withFont:lineBreakMode:alignment:' is deprecated: first deprecated in iOS 7.0 - Use -drawInRect:withAttributes:

つまり、既存のdrawInRect:withFont:lineBreakMode:alignment:メソッドを使用することはiOS 7.0からは非推奨なので、drawInRect:withAttributes:メソッドを使うようにしましょう、ということです。

さて、以下のサンプルコードをiOS 7.0向けにdrawInRect:withAttributes:メソッドを使うように変更してみましょう。

iOS 7.0までの文字列描画

// フォントオブジェクトを生成する
UIFont *font = [UIFont boldSystemFontOfSize:11.0];

// 文字は白色で描画する
[[UIColor whiteColor] set];
    
// text を描画する
[text drawInRect:CGRectMake(0, 0, 320, 50) 
        withFont:font
   lineBreakMode:NSLineBreakByClipping
       alignment:NSTextAlignmentCenter];

iOS 7.0からの文字列描画

// フォントオブジェクトを生成する
UIFont *font = [UIFont boldSystemFontOfSize:11.0];

// パラグラフで文字の描画位置などを指定する
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByWordWrapping;
style.alignment = NSTextAlignmentCenter;

// text の描画する際の設定(属性)を指定する
NSDictionary *attributes = @{
    NSForegroundColorAttributeName : [UIColor whiteColor],
    NSFontAttributeName : font,
    NSParagraphStyleAttributeName : style
};

// text を描画する
[text drawInRect:CGRectMake(0, 0, 320, 50) withAttributes:attributes];