2016-09-21 1 views
1

私はカスタムテーブルビューセルを作成しました。そのセルにいくつかの文字列を表示したいと思います。私はバックエンドから文字列を取得するので、必要なラベルの数はわかりません。私は1つのラベルで文字列を連結しようとしましたが、以下のように実装しましたが、char ":"の後に別の属性を持つ文字列を表示したいと考えています。カスタムテーブルビューセル内の動的UILabels数

for (AttributesModel* attribute in model.attributes) { 
    NSString *attributeName = attribute.name; 
    attributeString = [[attributeString stringByAppendingString: attributeName] mutableCopy]; 
    attributeString = [[attributeString stringByAppendingString: @" : "] mutableCopy]; 
    for (NSDictionary *value in attribute.options) { 
     attributeString = [[attributeString stringByAppendingString: [value objectForKey:@"name"] ] mutableCopy]; 
     attributeString = [[attributeString stringByAppendingString: @", "] mutableCopy]; 
    } 
    attributeString = [[attributeString stringByAppendingString: @"\n"] mutableCopy]; 
} 

char ":"の後にある文字列の属性を変更できませんでした。 これを行う方法はありますか?セルに動的な数のラベルを作成したり、「:」の後にのみ配置される文字列の属性を変更することはできますか?

答えて

1

UILabel内のテキストセクションの書式設定などの属性を変更したいように思えます。

  1. 文字列の属性変更可能コピーの作成(NSStringをNSMutableAttributedStringに変換するa.k.a)を作成します。
  2. 属性をこのコピーの一部に変更します。
  3. ラベルのattributedTextプロパティを属性付き文字列に設定します。あなたがCharacter Attributes referenceを参照してください、あなたの辞書に設定できる属性のリストについては
NSString *myString = @"This is my string"; 
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:myString]; 
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy]; 

// The range of text to change, i.e. start from the 5th index 
// (starting from 0 like arrays), and continue for 2 characters: 
NSRange rangeOfSecondWord = NSMakeRange(5, 2); 

// The list of attributes to apply to that range: 
NSDictionary *myAttributes = @{ 
           NSForegroundColorAttributeName : [UIColor redColor], 
           }; 

// Actually apply the attributes: 
[mutableAttributedString setAttributes:myAttributes range:rangeOfSecondWord]; 

// Set the text of the label to the attributed string: 
myLabel.attributedText = mutableAttributedString; 

文字列をダウンロードしているので、あらかじめ範囲を知ることができない場合があります。それらを連結しているので、範囲を動的に見つける方法は次のとおりです。

NSString *stringOne = @"My name is "; 
NSString *stringTwo = @"John Citizen"; 
NSString *joinedStrings = [stringOne stringByAppendingString:stringTwo]; 

NSRange rangeOfStringTwo = [joinedStrings rangeOfString:stringTwo]; 
関連する問題