0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【画像】【コード】【例付き】特定のLabelの文字の色を変える

Posted at

① UILabelの紐付け

@IBOutlet weak var label: UILabel!

② 色を変える単語を指定

// ストーリーボードで設定されたテキストを取得
let fullText = label.text ?? ""
        
// Attributed Stringの作成
let attributedString = NSMutableAttributedString(string: fullText)
        
 // 変更したい部分の範囲を指定
let range = (fullText as NSString).range(of: "ここに色を変える単語")
        
// 属性を設定
attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: range)
        
// UILabelに設定
label.attributedText = attributedString

↓ここで好きな色に指定

// 属性を設定
attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: range)

変更前

スクリーンショット 2024-10-23 12.36.41.png

変更後

スクリーンショット 2024-10-23 12.40.10.png


// ストーリーボードで設定されたテキストを取得
let fullText = label.text ?? ""
                
// Attributed Stringの作成
let attributedString = NSMutableAttributedString(string: fullText)
                
// 変更したい部分の範囲を指定
let range = (fullText as NSString).range(of: "カレー")
                
// 属性を設定
attributedString.addAttribute(.foregroundColor, value: UIColor.brown, range: range)
                
// UILabelに設定
label.attributedText = attributedString
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?