1. ホーム
  2. ios

[解決済み] 1つのラベルで複数のフォントカラーを使用する

2022-12-01 23:27:01

質問

iOS で 1 つのラベルに 2 つ、あるいは 3 つのフォント色を使用する方法はありますか?

例として "hello, how are you" というテキストを使用した場合、"hello," は青、"how are you" は緑になりますか。

複数のラベルを作成するよりも簡単そうですが、可能でしょうか?

どのように解決するのですか?

ここから参照。

まず最初に初期化するのは NSString NSMutableAttributedString を以下のようにします。

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()

ViewDidLoad

override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
    // set label Attribute
    labName.attributedText = myMutableString
    super.viewDidLoad()
}

出力

マルチカラー

ViewDidLoadに以下の行コードを追加して、複数の色を文字列で取得します。

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

マルチカラー出力

スウィフト 4

var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

Swift 5.0

 var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
 myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))