9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSString stringWithFormatの引数の便利な指定

Last updated at Posted at 2015-05-31

引数の場所の指定ができる

+ (instancetype)stringWithFormat:(NSString *)format

objective-cで文字列を生成する↑のメソッド。
%[引数番号]$@のように指定すると引数を任意の場所に挿入することができる。
びっくり。

    NSString *sampleStr = [NSString stringWithFormat:@"%1$@くんと%2$@ちゃんが歩いていました。%1$@くんはお花を持っていました", @"タカシ", @"ハナコ"];

//=>タカシくんとハナコちゃんが歩いていました。タカシくんはお花を持っていました

どこで役に立つ?

私はautolayoutのVFLを指定する時に使ってます。
Viewの指定を取り回しできるので楽。

    //VFLで文字列をまとめる
    NSString *horizontalFormat      =   [NSString stringWithFormat:@"H:|-20-[%@]-20-|", topViewKey];
    NSString *addHorizontalFormat   =   [NSString stringWithFormat:@"H:|-20-[%1$@]-20-[%2$@(==%1$@)]-20-|", leftViewKey,rightViewKey];
    NSString *verticalFormat        =   [NSString stringWithFormat:@"V:|-88-[%1$@]-20-[%2$@(==%1$@)]-20-|", topViewKey, leftViewKey];
    NSString *addVertivalFormat     =   [NSString stringWithFormat:@"V:|-88-[%1$@]-20-[%2$@(==%1$@)]-20-|", topViewKey, rightViewKey];
    

以上です!

9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?