3

異なる色のラベルを作成する最も簡単な方法は何ですか?

たとえば、
「ジョン・ジョンソンがあなたにメッセージを送信しました」という メッセージを表示したいと思います。

しかし、それは青色で 、残りのメッセージは黒色John Johnsonで表示されるようにしたいと思います。

4

6 に答える 6

4

文字列内の個々の文字または文字の範囲に適用される属性(フォントやカーニングなど)と、TTTAttributedLabelように視覚化できるカスタムラベルコントロールを設定するには、NSAttributedStringクラス(または可変クラス- )が必要です。NSMutableAttributedStringNSAttributedString

于 2012-08-14T10:41:02.177 に答える
3

UILabelでは基本的に不可能です。これを行う場合は、オーバーライドする必要がありますdrawTextInRect。ただし、OHAttributedLabelをお勧めします。これにはattributedStringがあり、範囲を指定するためにtextcolorを設定できます。

于 2012-08-14T10:41:25.047 に答える
2

を使用しUIWebViewます。

webView.text = 
  @"<span style:\"color:blue;\">John Johnson</span> sent you a message.";
于 2012-08-14T10:38:52.990 に答える
1

CoreTextを使用します。お役に立てれば。

于 2012-08-14T11:19:19.213 に答える
0

これを行うためにUILabel拡張機能を作成しました。基本的には、NSAttributedStringを使用して特定の範囲の色を定義します:https ://github.com/joaoffcosta/UILabel-FormattedText

この動作を自分で実装したい場合は、次のようにしてください。

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: @"John Johnson sent you a message"];
[text addAttribute: NSFontAttributeName
             value: font
             range: range];
[self setAttributedText: text];
于 2013-03-04T11:53:42.007 に答える
0

これをswiftで試してください(次の拡張子を持つコードを実行してください)

extension NSMutableAttributedString {

    func setColorForText(textToFind: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

UILabelで拡張機能を試してください:

let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let stringValue = "John Johnson sent you a message"  // or direct assign single string value like "firstsecondthird"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: "John Johnson", withColor: UIColor.blue)
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

結果は次のとおりです。

ここに画像の説明を入力してください

于 2017-10-24T10:10:19.193 に答える