128

私が抱えている問題は、TextView 内の特定のテキストの textColor を変更できるようにしたいということです。連結された文字列を使用していますが、TextView のテキストに追加する文字列が必要です。私が使いたいのはNSMutableAttributedStringのようですが、Swift でこれを使用する方法に関するリソースが見つかりません。私がこれまでに持っているものは次のようなものです:

let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString

ここから、textColor を変更する必要がある単語の範囲を見つけて、それらを属性付き文字列に追加する必要があることがわかります。私が知る必要があるのは、attributedString から正しい文字列を見つけて、textColor を変更する方法です。

評価が低すぎるので、自分の質問に答えることはできませんが、ここに私が見つけた答えがあります

からいくつかのコードを翻訳することで、自分の答えを見つけました

NSAttributedString の部分文字列の属性を変更する

Swift での実装例を次に示します。

let string = "A \(stringOne) and \(stringTwo)"
var attributedString = NSMutableAttributedString(string:string)

let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
for stringOneMatch in stringOneMatches {
    let wordRange = stringOneMatch.rangeAtIndex(0)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
}

textView.attributedText = attributedString

複数の文字列の textColor を変更したいので、これを処理するヘルパー関数を作成しますが、これは textColor を変更するために機能します。

4

25 に答える 25

140
let mainString = "Hello World"
let stringToColor = "World"

スイフト5

let range = (mainString as NSString).range(of: stringToColor)

let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)

textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString

スイフト 4.2

let range = (mainString as NSString).range(of: stringToColor)
    

let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)     
    
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
于 2016-09-22T13:11:44.563 に答える
112

質問に多少答えたようですが、正規表現を使用せずにもう少し簡潔な方法を提供して、タイトルの質問に答えます。

テキストの長さの色を変更するには、文字列内の色付けされる文字の開始インデックスと終了インデックスを知る必要があります。

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

次に、属性付きの文字列に変換し、NSForegroundColorAttributeName で「属性の追加」を使用します。

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

設定できるその他の標準属性のリストは、Apple のドキュメントにあります。

于 2014-08-11T16:52:43.117 に答える
48

スウィフト 2.1 アップデート:

 let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
 let linkTextWithColor = "click here"

 let range = (text as NSString).rangeOfString(linkTextWithColor)

 let attributedString = NSMutableAttributedString(string:text)
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

 self.helpText.attributedText = attributedString

self.helpTextUILabelアウトレットです。

于 2016-01-03T12:45:29.853 に答える
33

Swift 4.2Swift 5は、文字列の一部に色を付けます。

String を拡張しながら NSMutableAttributedString を使用する非常に簡単な方法です。これは、文字列全体で複数の単語を色付けするためにも使用できます。

import UIKit

extension String {
    func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        for string in strings {
            let range = (self as NSString).range(of: string)
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        }

        guard let characterSpacing = characterSpacing else {return attributedString}

        attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))

        return attributedString
    }
}

これで、必要なビューコントローラーでグローバルに使用できるようになりました:

let attributedWithTextColor: NSAttributedString = "Doc, welcome back :)".attributedStringWithColor(["Doc", "back"], color: UIColor.black)

myLabel.attributedText = attributedWithTextColor

swift 4 でテキストの色付けを使用する例

于 2019-01-29T08:29:04.520 に答える
10

クリスの答えは私にとって大きな助けになったので、彼のアプローチを使用して、再利用できる機能に変えました。これにより、文字列の残りの部分に別の色を与えながら、部分文字列に色を割り当てることができます。

static func createAttributedString(fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) -> NSMutableAttributedString
{
    let range = (fullString as NSString).rangeOfString(subString)
    let attributedString = NSMutableAttributedString(string:fullString)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: fullStringColor, range: NSRange(location: 0, length: fullString.characters.count))
    attributedString.addAttribute(NSForegroundColorAttributeName, value: subStringColor, range: range)
    return attributedString
}
于 2016-09-22T15:10:12.253 に答える
6

この拡張機能を使用できます 私はそれをテストします

スウィフト4.2

import Foundation
import UIKit

extension NSMutableAttributedString {

    convenience init (fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) {
           let rangeOfSubString = (fullString as NSString).range(of: subString)
           let rangeOfFullString = NSRange(location: 0, length: fullString.count)//fullString.range(of: fullString)
           let attributedString = NSMutableAttributedString(string:fullString)
           attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: fullStringColor, range: rangeOfFullString)
           attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: subStringColor, range: rangeOfSubString)

           self.init(attributedString: attributedString)
   }

}
于 2018-09-17T06:37:07.070 に答える
4

スイフト 2.2

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "1234567890", attributes: [NSFontAttributeName:UIFont(name: kDefaultFontName, size: 14.0)!])

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0/255.0, green: 125.0/255.0, blue: 179.0/255.0, alpha: 1.0), range: NSRange(location:0,length:5))

self.lblPhone.attributedText = myMutableString
于 2016-10-13T09:01:24.620 に答える
3

これはあなたのために働くかもしれません

let main_string = " User not found,Want to review ? Click here"
    let string_to_color = "Click here"

    let range = (main_string as NSString).range(of: string_to_color)

    let attribute = NSMutableAttributedString.init(string: main_string)
    attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue , range: range)

    lblClickHere.attributedText = attribute
于 2019-01-01T07:55:05.653 に答える
2

この拡張機能は、既定の色が既に設定されているラベルのテキストを構成するときにうまく機能します。

public extension String {
    func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
        let range = (self as NSString).range(of: substring)
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        return attributedString
    }
}

例えば

let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")

let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText
于 2021-01-30T09:29:02.250 に答える
2

簡単な拡張として使用できます

extension String{

func attributedString(subStr: String) -> NSMutableAttributedString{
    let range = (self as NSString).range(of: subStr)
    let attributedString = NSMutableAttributedString(string:self)
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
    
    return attributedString
  }
}

myLable.attributedText = fullStr.attributedString(subStr: strToChange)

  
于 2020-08-05T10:12:01.497 に答える
0

cocoapod Prestylerを確認してください:

Prestyler.defineRule("$", UIColor.orange)
label.attributedText = "This $text$ is orange".prestyled()
于 2019-03-04T18:50:03.440 に答える