2017-11-17 4 views
1

enter image description here異なる色で2つのラベルを動的に表示する方法は?

「イメージはまだ返されています....」と参照してください。その後、1つのカウント値が存在します(7)。

ここで、メッセージの色は青で、カウント値は(7)が緑色です。

私の質問は、画像に示されているように、異なる長さと異なる色で両方のラベルを動的に調整する方法です。

+0

あなたはそのためNSLayoutConstraintを使用することができます... – Larme

+1

NSAttributedStringは、あなたがこの –

+1

のためにそれを使用することができますしようと試みたコード –

答えて

0

あなたは、この例のようNSAttributedStringを使用することができます。

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"I still look back on that expe.... (7)"]; 
[string setColorForText:@"I still look back on that expe...." withColor:[UIColor blueColor]]; 
[string setColorForText:@"(7)" withColor:[UIColor greenColor]]; 
mylabel.attributedText = string; 

それとも、ストーリーボードに制約を使用することができます。 これは簡単なことですが、Content Hugging PriorityContent Compression Resistance Priorityの値を使用して、最初のラベルを減らして別のラベルに貼り付ける必要があります。

ご希望の場合は、その方法を詳しく説明できます。

EDIT:あなたはNSTextAttachmentを使用することができ、画像を追加するには

NSString *firstPart = @"I still look back on that expe...."; 
NSString *secondPart = @"(7)"; 

NSAttributedString *firstAttrStr = [[NSAttributedString alloc] initWithString:firstPart attributes:@{ NSForegroundColorAttributeName : [UIColor blueColor] }]; 
NSAttributedString *secondAttrStr = [[NSAttributedString alloc] initWithString:secondPart attributes:@{ NSForegroundColorAttributeName : [UIColor greenColor] }]; 

NSMutableAttributedString* result = [firstAttrStr mutableCopy]; 
[result appendAttributedString:secondAttrStr]; 

self.label.attributedText = result; 

あなたはこのコードを試すことができます。

+0

私はあなたのコードを試しました、それは動作しますが、静的なものです。 –

+0

@NikitaPatil動的に使用するための編集を参照してください。 – Kerberos

+0

更新されたコードが私のために動的に動作します。ありがとうございます。 –

0

2つのラベルを使用することは、そのやり方ではありません。はるかに良い解決策は、NSAttributedStringを使用することです。

struct MyMsg { 
     var text: String 
     var count: Int 
    } 

    let msg = MyMsg(text: "I still look back on that expe....", count: 7) 

    let contentString = NSMutableAttributedString(string: msg.text) 
    let countString = NSAttributedString(string: " \(msg.count)", attributes: [NSForegroundColorAttributeName: UIColor.green]) 
    contentString.append(countString) 
    myLabel.attributedText = contentString 
+0

Objective cのurコードを説明してください。私はスイフトを知らない。 –

関連する問題