code

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

starcafe 2023. 6. 2. 20:40
반응형

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

문제는 텍스트 보기에서 특정 텍스트의 textColor를 변경할 수 있어야 한다는 것입니다.연결된 문자열을 사용하고 있으며 TextView의 텍스트에 추가할 문자열을 원합니다.은 내가사싶은것은고하인 것 같습니다.NSMutableAttributedString하지만 스위프트에서 이걸 어떻게 사용하는지에 대한 정보를 찾을 수가 없습니다.지금까지 제가 가진 것은 다음과 같습니다.

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

여기서 textColor를 변경해야 하는 단어의 범위를 찾은 다음 속성 문자열에 추가해야 합니다.제가 알아야 할 것은 속성된 문자열에서 올바른 문자열을 찾은 다음 textColor를 변경하는 방법입니다.

저는 평점이 너무 낮아서 제 질문에 답할 수 없지만, 여기 제가 찾은 답이 있습니다.

나는 몇몇 코드를 번역해서 나만의 답을 찾았습니다.

NSA 특성 문자열의 하위 문자열 속성 변경

다음은 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를 변경할 수 있습니다.

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

SWIFT 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

질문에 어느 정도 답변하셨지만, 제목 질문에 regex를 사용하지 않고 조금 더 간결한 방법을 제공하기 위해:

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

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

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

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

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

설정할 수 있는 추가 표준 속성 목록은 Apple 설명서에서 확인할 수 있습니다.

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.helpText입니다.UILabel아웃렛

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

문자열을 확장하는 동안 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와 함께 텍스트 색상 사용 예제

답변은 이미 이전 게시물에서 제공되었지만 저는 이를 수행하는 다른 방법을 가지고 있습니다.

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

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

크리스의 답변이 저에게 큰 도움이 되었기 때문에 그의 접근법을 사용하여 재사용할 수 있는 펑으로 변했습니다.이것은 부분 문자열에 색을 지정하고 나머지 문자열에는 다른 색을 지정합니다.

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]

이 확장자를 사용할 수 있습니다. 다시 테스트해 보겠습니다.

swift 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)
   }

}

스위프트 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

색상, 글꼴 등과 같은 다른 스타일로 레이블을 수행하는 가장 쉬운 방법은 속성 관리자에서 "속성" 속성을 사용하는 것입니다.텍스트의 일부를 선택하고 원하는 대로 변경합니다.

여기에 이미지 설명 입력

문자열 확장명을 만들기 전의 답변을 기준으로 함

extension String {

func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
     let range = (self as NSString).range(of: highlightedWords)
     let result = NSMutableAttributedString(string: self)

     for attribute in attributes {
         result.addAttributes(attribute, range: range)
     }

     return result
    }
}

텍스트의 속성을 메서드에 전달할 수 있습니다.

이렇게 부르세요.

  let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
  myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)

스위프트 4.1

나는 이 인 스위프트 3에서 바뀌었습니다.

let str = "Welcome "
let welcomeAttribute = [ NSForegroundColorAttributeName: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)

그리고 이것은 Swift 4.0에서

let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)

스위프트 4.1로

let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey(rawValue: NSForegroundColorAttributeName): UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)

잘 작동함

swift 4.2

    let textString = "Hello world"
    let range = (textString as NSString).range(of: "world")
    let attributedString = NSMutableAttributedString(string: textString)

    attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
    self.textUIlable.attributedText = attributedString

당신에게 도움이 될 수도 있습니다.

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

이 간단한 기능으로 텍스트를 할당하고 선택한 단어를 강조 표시할 수 있습니다.

UI 텍스트 보기를 UI 레이블 등으로 변경할 수도 있습니다.

func highlightBoldWordAtLabel(textViewTotransform: UITextView, completeText: String, wordToBold: String){
    textViewToTransform.text = completeText
    let range = (completeText as NSString).range(of: wordToBold)
    let attribute = NSMutableAttributedString.init(string: completeText)

    attribute.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 16), range: range)
    attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)
    textViewToTransform.attributedText = attribute
}

"텍스트의 여러 단어에 특정 색상 적용"을 원하는 모든 사용자를 위해 NSRegular Expression을 사용하여 수행할 수 있습니다.

 func highlight(matchingText: String, in text: String) {
    let attributedString  = NSMutableAttributedString(string: text)
    if let regularExpression = try? NSRegularExpression(pattern: "\(matchingText)", options: .caseInsensitive) {
        let matchedResults = regularExpression.matches(in: text, options: [], range: NSRange(location: 0, length: attributedString.length))
        for matched in matchedResults {
             attributedString.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.yellow], range: matched.range)

        }
        yourLabel.attributedText = attributedString
    }
}

참조 링크: https://gist.github.com/aquajach/4d9398b95a748fd37e88

단순 확장으로 사용할 수 있습니다.

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)

  

이 확장명은 이미 설정된 기본 색상으로 레이블의 텍스트를 구성할 때 잘 작동합니다.

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

아주 쉬운 방법입니다.

let text = "This is a colorful attributed string"
let attributedText = 
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))

자세한 내용은 여기를 클릭하십시오. https://github.com/iOSTechHub/AttributedString

글꼴 색을 변경하려면 먼저 아래 이미지와 같이 일반적인 색 대신 속성을 선택합니다.

그런 다음 속성 필드에서 텍스트를 선택한 다음 선형의 오른쪽에 있는 색상 버튼을 선택해야 합니다.이렇게 하면 색이 바뀝니다.

이 방법을 사용할 수 있습니다.저는 이 방법을 공통 유틸리티 클래스에서 구현하여 전체적으로 액세스했습니다.

func attributedString(with highlightString: String, normalString: String, highlightColor: UIColor) -> NSMutableAttributedString {
    let attributes = [NSAttributedString.Key.foregroundColor: highlightColor]
    let attributedString = NSMutableAttributedString(string: highlightString, attributes: attributes)
    attributedString.append(NSAttributedString(string: normalString))
    return attributedString
}

Swift 3x 및 UITextView를 사용하는 경우 NS ForgroundColorAttributeName이 작동하지 않을 수 있습니다(어떤 접근 방식을 시도했더라도 작동하지 않았습니다).

그래서, 저는 좀 더 조사한 후에 해결책을 찾았습니다.

//Get the textView somehow
let textView = UITextView()
//Set the attributed string with links to it
textView.attributedString = attributedString
//Set the tint color. It will apply to the link only
textView.tintColor = UIColor.red

속성 문자열의 매개 변수가 아닌 텍스트 보기 매개 변수를 변경해야 합니다.

textView.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.red,
        NSAttributedString.Key.underlineColor: UIColor.red,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
    ]

코코아 포드 Prestyler를 확인하십시오.

Prestyler.defineRule("$", UIColor.orange)
label.attributedText = "This $text$ is orange".prestyled()
extension String{
// to make text field mandatory * looks
mutating func markAsMandatoryField()-> NSAttributedString{

    let main_string = self
    let string_to_color = "*"
    let range = (main_string as NSString).range(of: string_to_color)
    print("The rang = \(range)")
    let attribute = NSMutableAttributedString.init(string: main_string)
    attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.rgbColor(red: 255.0, green: 0.0, blue: 23.0) , range: range)
     return attribute
}

}

EmailLbl.attribute 사용텍스트 = EmailLbl.text!필수 필드로 표시()

언급URL : https://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift

반응형