2016-12-08 6 views
1

ラベルに渡す文字列の配列内の特定のテキストの色を変更するにはどうすればよいですか?文字列の配列内の特定のテキストの色を変更します。 Swift

var stringData = ["First one", "Please change the color", "don't change me"] 

そして、それはいくつかのラベルに渡されています:「」内の単語の色を変更するのが最善の方法を何

Label1.text = stringData[0] 
Label2.text = stringData[1] 
Label3.text = stringData[2] 

のは、私は、文字列の配列を持っているとしましょうstringData [1]?

ありがとうございました!

+0

使用NSAttributedString。 –

+0

この質問を確認することができます [単一のラベルで複数のフォント色を使用する - Swift](http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift) ) – hooliooo

+0

[SwiftでNSMutableAttributedStringを使用して特定のテキストの色を変更する]の可能な複製(http://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift) –

答えて

4
let str = NSMutableAttributedString(string: "Please change the color") 
str.addAttributes([NSForegroundColorAttributeName: UIColor.red], range: NSMakeRange(14, 3)) 
label.attributedText = str 

rangeは、特定のテキストの範囲です。

1

あなたは、文字列内のすべてのtheの色を変更したい場合:

func highlight(word: String, in str: String, with color: UIColor) -> NSAttributedString { 
    let attributedString = NSMutableAttributedString(string: str) 
    let highlightAttributes = [NSForegroundColorAttributeName: color] 

    let nsstr = str as NSString 
    var searchRange = NSMakeRange(0, nsstr.length) 

    while true { 
     let foundRange = nsstr.range(of: word, options: [], range: searchRange) 
     if foundRange.location == NSNotFound { 
      break 
     } 

     attributedString.setAttributes(highlightAttributes, range: foundRange) 

     let newLocation = foundRange.location + foundRange.length 
     let newLength = nsstr.length - newLocation 
     searchRange = NSMakeRange(newLocation, newLength) 
    } 

    return attributedString 
} 

label2.attributedText = highlight(word: "the", in: stringData[1], with: .red) 
関連する問題