[ios] Swift에서 NSMutableAttributedString을 사용하여 특정 텍스트의 색상 변경

내가 가진 문제는 TextView에서 특정 텍스트의 textColor를 변경할 수 있기를 원한다는 것입니다. 연결된 문자열을 사용하고 있으며 TextView의 텍스트에 추가하는 문자열을 원합니다. 내가 사용하고 싶은 것은 NSMutableAttributedString이지만 Swift에서 이것을 사용하는 방법에 대한 리소스를 찾지 못했습니다. 지금까지 내가 가진 것은 다음과 같습니다.

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

여기에서 textColor를 변경해야하는 단어의 범위를 찾아 속성 문자열에 추가해야한다는 것을 알고 있습니다. 내가 알아야 할 것은 attributeString에서 올바른 문자열을 찾은 다음 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를 변경하는 데 효과적입니다.



답변

질문에 다소 대답했지만 제목 질문에 대답하기 위해 정규식을 사용하지 않고 약간 더 간결한 방법을 제공하기 위해 :

텍스트 길이의 색상을 변경하려면 문자열에서 색상이 지정 될 문자의 시작 및 끝 색인을 알아야합니다.

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

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

그런 다음 속성 문자열로 변환하고 NSForegroundColorAttributeName과 함께 ‘add attribute’를 사용합니다.

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

설정할 수있는 추가 표준 속성 목록은 Apple 문서 에서 찾을 수 있습니다.


답변

SWIFT 5

let main_string = "Hello World"
let string_to_color = "World"

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

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


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

SWIFT 4.2

 let txtfield1 :UITextField!

    let main_string = "Hello World"
    let string_to_color = "World"

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

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


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


답변

Swift 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.helpTextA는 UILabel콘센트.


답변

Swift 4.2Swift 5 는 문자열의 일부를 채색합니다.

문자열을 확장하는 동안 NSMutableAttributedString을 사용하는 매우 쉬운 방법입니다. 이것은 전체 문자열에서 하나 이상의 단어를 채색하는 데에도 사용할 수 있습니다.

확장자를위한 새 파일을 추가합니다. File-> New-> ex. “NSAttributedString + TextColouring”및 코드 추가

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로 텍스트 채색 사용 예


답변

답변은 이미 이전 게시물에서 제공되었지만 다른 방법이 있습니다.

Swift 3x :

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "Your full label textString")

myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
        , NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give

yourLabel.attributedText = myMutableString

이것이 누구에게나 도움이되기를 바랍니다!


답변

Chris의 대답은 저에게 큰 도움이 되었기 때문에 그의 접근 방식을 사용하여 재사용 할 수있는 기능으로 전환되었습니다. 이렇게하면 나머지 문자열에 다른 색상을 부여하면서 하위 문자열에 색상을 할당하겠습니다.

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
}


답변

스위프트 4.1

NSAttributedStringKey.foregroundColor

예를 들어 NavBar에서 글꼴을 변경하려는 경우 :

self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]