programing

Swift를 사용하여 Attributed String을 작성하려면 어떻게 해야 합니까?

stoneblock 2023. 4. 19. 21:53

Swift를 사용하여 Attributed String을 작성하려면 어떻게 해야 합니까?

간단한 커피 계산기를 만들려고 합니다.커피의 양을 그램 단위로 표시해야 합니다.양을 표시하기 위해 사용하는 UILabel에 그램의 "g" 기호를 붙여야 합니다.UILabel의 숫자는 사용자 입력만으로 동적으로 변화하고 있지만 업데이트 번호와 다른 형식의 문자열 끝에 소문자 "g"를 추가해야 합니다.숫자의 크기와 위치가 변경되면 숫자와 함께 "g"가 움직이도록 숫자에 "g"를 부착해야 합니다.이 문제는 이미 해결이 되었기 때문에 올바른 방향으로의 링크를 검색해 두면 도움이 될 것 같습니다.

문서를 통해 속성 문자열을 검색하여 앱스토어에서 "속성 문자열 생성자"까지 다운받았지만, 결과 코드는 Objective-C에 있으며 Swift를 사용하고 있습니다.Swift에서 속성 문자열을 사용하여 커스텀 속성을 가진 커스텀 폰트를 작성하는 것은 이 언어를 학습하는 다른 개발자에게도 도움이 될 수 있습니다.그 방법에 대한 명확한 경로가 없기 때문에 이에 대한 문서는 매우 혼란스럽습니다.저의 계획은 속성 문자열을 생성하여 coffeeAmount 문자열 끝에 추가하는 것입니다.

var coffeeAmount: String = calculatedCoffee + attributedText

여기서 calculatedCoffee는 문자열로 변환된 Int이고 "attributedText"는 작성하려는 커스터마이즈된 글꼴을 가진 소문자 "g"입니다.내가 잘못된 방향으로 가고 있는 것 같아.어떤 도움이라도 감사합니다!

여기에 이미지 설명 입력

이 답변은 Swift 4.2용으로 업데이트되었습니다.

퀵 레퍼런스

Attributed String을 작성 및 설정하는 일반적인 형식은 다음과 같습니다.기타 일반적인 옵션은 다음과 같습니다.

// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) 

// set attributed text on a UILabel
myLabel.attributedText = myAttrString

텍스트 색상

let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]

배경색

let myAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]

폰트

let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]

여기에 이미지 설명 입력

let myAttribute = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ]

여기에 이미지 설명 입력

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [ NSAttributedString.Key.shadow: myShadow ]

이 투고의 나머지 부분은 관심 있는 분들을 위해 더 자세한 내용을 제공합니다.


특성

입니다.[NSAttributedString.Key: Any]서, snowledge.NSAttributedString.Key으로 Atribute는 Atribute입니다.Any는 일부 유형의 값입니다.값은 글꼴, 색상, 정수 또는 다른 것이 될 수 있습니다.재빠르다예를 들어 다음과 같습니다.

  • 이름: " " " 입니다.NSAttributedString.Key.fonta , :: aUIFont
  • 이름: " " " 입니다.NSAttributedString.Key.foregroundColora , :: aUIColor
  • 이름: " " " 입니다.NSAttributedString.Key.linka , : :NSURL ★★★★★★★★★★★★★★★★★」NSString

다른 많은 것들이 있다.자세한 내용은 이 링크를 참조하십시오.다음과 같은 사용자 지정 속성을 만들 수도 있습니다.

  • 이름: " " " 입니다.NSAttributedString.Key.myName 유형 값: " " " " " 。
    내선번호를 지정한 경우:

    extension NSAttributedString.Key {
        static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey")
    }
    

Swift에서 특성 생성

다른 사전을 선언하는 것과 마찬가지로 속성을 선언할 수 있습니다.

// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]

// multiple attributes declared at once
let multipleAttributes: [NSAttributedString.Key : Any] = [
    NSAttributedString.Key.foregroundColor: UIColor.green,
    NSAttributedString.Key.backgroundColor: UIColor.yellow,
    NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]

// custom attribute
let customAttribute = [ NSAttributedString.Key.myName: "Some value" ]

해 주세요.rawValue밑줄 스타일에 필요한 값입니다.

속성은 사전일 뿐이므로 빈 사전을 만든 다음 키-값 쌍을 추가하여 만들 수도 있습니다.값에 여러 유형이 포함된 경우 유형으로 사용해야 합니다.여기 있습니다multipleAttributes위의 예에서는 다음과 같이 재현됩니다.

var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue

속성 문자열

아트리뷰트를 이해했습니다.아트리뷰트 문자열을 만들 수 있습니다.

초기화

Attributed String(속성 문자열) 를 사용할 수 .NSAttributedString초기화하는 방법은 다음과 같습니다.

// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)

또는 해야 할 를 사용하십시오.NSMutableAttributedString선언은 매우 유사합니다.

// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()

// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.", attributes: myAttributes2)

Attributed String 변경

예를 들어, 이 투고 상단에 Attribute String을 클릭합니다.

" " " 를 .NSMutableAttributedString새 글꼴 속성을 사용합니다.

let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )

있는 는, 을 「Attribute string」으로합니다.UITextView (오류)UILabel는 이렇게 말합니다

textView.attributedText = myString

사용 안 함textView.text.

결과는 다음과 같습니다.

여기에 이미지 설명 입력

있지 Atribute 문자열을 가 Atribute가 아닌 Atribute String을 도 Atribute가 되어 있지 않습니다.letmyString 수정할 수 요. '아까', '아까', '아까', '아까', '아까'이기 때문에. 왜냐하면 그것은 여전히NSMutableAttributedString이것은 나에게 다소 자유롭지 않은 것으로 보이며, 향후에 이것이 바뀌어도 놀라지 않을 것입니다.」를 참조해 주세요).

let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)

여기에 이미지 설명 입력

''이라는 즉 색인에서 시작하는 '끈을.17가 ㅇㅇㅇㅇㅇㅇㅇㅇ다.7. 이것은, 다음의 점에 주의해 주세요.NSRangeRange. (범위에 대한 자세한 내용은 이 답변을 참조하십시오.)addAttribute첫에, Atribute 을 두 위치에를 세 배치할 수 있습니다.

var myRange = NSRange(location: 17, length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: myRange)

여기에 이미지 설명 입력

이치노다양성은 '먹다', '먹다', '먹다'를 사용해볼까요addAttributes(method (method)에 주의)s이 메서드에서는 여러 Atribute를 동시에 추가할 수 있지만, 다시 1개만 추가합니다.

myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)

여기에 이미지 설명 입력

속성이 중복되는 곳이 있습니다.속성을 추가해도 이미 있는 속성은 덮어쓰지 않습니다.

관련된

상세 정보

Swift를 합니다.NSMutableAttributedStringObj-C'를합니다.계산된 값을 문자열로 전달하여 인스턴스화합니다.

var attributedString = NSMutableAttributedString(string:"\(calculatedCoffee)")

, 이제 '아트리뷰트'라는 .gstring(스트링)주의: UIFont.systemFontOfSize(_)이 있는 이니셜라이저가하기 전에 개봉해야 .

var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(19.0)!]
var gString = NSMutableAttributedString(string:"g", attributes:attrs)

그런 다음 첨부합니다.

attributedString.appendAttributedString(gString)

다음으로 다음과 같이 NSAttributedString을 표시하도록 UILabel을 설정할 수 있습니다.

myLabel.attributedText = attributedString

속성 문자열은 라이브러리를 사용하는 것을 강력히 추천합니다.예를 들어 4가지 색상과 4가지 글꼴을 가진 문자열 하나를 원할 때 훨씬 더 쉬워집니다.여기 제가 제일 좋아하는 게 있어요.이것은 SwiftyAttributes라고 불립니다.

SwiftyAttributes를 사용하여 4가지 색상과 글꼴이 다른 문자열을 만드는 경우:

let magenta = "Hello ".withAttributes([
    .textColor(.magenta),
    .font(.systemFont(ofSize: 15.0))
    ])
let cyan = "Sir ".withAttributes([
    .textColor(.cyan),
    .font(.boldSystemFont(ofSize: 15.0))
    ])
let green = "Lancelot".withAttributes([
    .textColor(.green),
    .font(.italicSystemFont(ofSize: 15.0))

    ])
let blue = "!".withAttributes([
    .textColor(.blue),
    .font(.preferredFont(forTextStyle: UIFontTextStyle.headline))

    ])
let finalString = magenta + cyan + green + blue

finalString라고

이미지로 표시

Xcode 6 버전:

let attriString = NSAttributedString(string:"attriString", attributes:
[NSForegroundColorAttributeName: UIColor.lightGrayColor(), 
            NSFontAttributeName: AttriFont])

Xcode 9.3 버전:

let attriString = NSAttributedString(string:"attriString", attributes:
[NSAttributedStringKey.foregroundColor: UIColor.lightGray, 
            NSAttributedStringKey.font: AttriFont])

Xcode 10, iOS 12, Swift 4:

let attriString = NSAttributedString(string:"attriString", attributes:
[NSAttributedString.Key.foregroundColor: UIColor.lightGray, 
            NSAttributedString.Key.font: AttriFont])

스위프트 5

let attrStri = NSMutableAttributedString.init(string:"This is red")
let nsRange = NSString(string: "This is red")
        .range(of: "red", options: String.CompareOptions.caseInsensitive)
attrStri.addAttributes([
    NSAttributedString.Key.foregroundColor : UIColor.red,
    NSAttributedString.Key.font: UIFont.init(name: "PTSans-Regular", size: 15.0) as Any
], range: nsRange)
self.label.attributedText = attrStri

여기에 이미지 설명 입력

Swift 4:

let attributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!, 
                  NSAttributedStringKey.foregroundColor: UIColor.white]

스위프트: xcode 6.1

    let font:UIFont? = UIFont(name: "Arial", size: 12.0)

    let attrString = NSAttributedString(
        string: titleData,
        attributes: NSDictionary(
            object: font!,
            forKey: NSFontAttributeName))

세부 사항

  • Swift 5.2, X코드 11.4 (11E146)

솔루션

protocol AttributedStringComponent {
    var text: String { get }
    func getAttributes() -> [NSAttributedString.Key: Any]?
}

// MARK: String extensions

extension String: AttributedStringComponent {
    var text: String { self }
    func getAttributes() -> [NSAttributedString.Key: Any]? { return nil }
}

extension String {
    func toAttributed(with attributes: [NSAttributedString.Key: Any]?) -> NSAttributedString {
        .init(string: self, attributes: attributes)
    }
}

// MARK: NSAttributedString extensions

extension NSAttributedString: AttributedStringComponent {
    var text: String { string }

    func getAttributes() -> [Key: Any]? {
        if string.isEmpty { return nil }
        var range = NSRange(location: 0, length: string.count)
        return attributes(at: 0, effectiveRange: &range)
    }
}

extension NSAttributedString {

    convenience init?(from attributedStringComponents: [AttributedStringComponent],
                      defaultAttributes: [NSAttributedString.Key: Any],
                      joinedSeparator: String = " ") {
        switch attributedStringComponents.count {
        case 0: return nil
        default:
            var joinedString = ""
            typealias SttributedStringComponentDescriptor = ([NSAttributedString.Key: Any], NSRange)
            let sttributedStringComponents = attributedStringComponents.enumerated().flatMap { (index, component) -> [SttributedStringComponentDescriptor] in
                var components = [SttributedStringComponentDescriptor]()
                if index != 0 {
                    components.append((defaultAttributes,
                                       NSRange(location: joinedString.count, length: joinedSeparator.count)))
                    joinedString += joinedSeparator
                }
                components.append((component.getAttributes() ?? defaultAttributes,
                                   NSRange(location: joinedString.count, length: component.text.count)))
                joinedString += component.text
                return components
            }

            let attributedString = NSMutableAttributedString(string: joinedString)
            sttributedStringComponents.forEach { attributedString.addAttributes($0, range: $1) }
            self.init(attributedString: attributedString)
        }
    }
}

사용.

let defaultAttributes = [
    .font: UIFont.systemFont(ofSize: 16, weight: .regular),
    .foregroundColor: UIColor.blue
] as [NSAttributedString.Key : Any]

let marketingAttributes = [
    .font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
    .foregroundColor: UIColor.black
] as [NSAttributedString.Key : Any]

let attributedStringComponents = [
    "pay for",
    NSAttributedString(string: "one",
                       attributes: marketingAttributes),
    "and get",
    "three!\n".toAttributed(with: marketingAttributes),
    "Only today!".toAttributed(with: [
        .font: UIFont.systemFont(ofSize: 16.0, weight: .bold),
        .foregroundColor: UIColor.red
    ])
] as [AttributedStringComponent]
let attributedText = NSAttributedString(from: attributedStringComponents, defaultAttributes: defaultAttributes)

완전한 예

솔루션 코드를 여기에 붙이는 것을 잊지 마세요.

import UIKit

class ViewController: UIViewController {

    private weak var label: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel(frame: .init(x: 40, y: 40, width: 300, height: 80))
        label.numberOfLines = 2
        view.addSubview(label)
        self.label = label

        let defaultAttributes = [
            .font: UIFont.systemFont(ofSize: 16, weight: .regular),
            .foregroundColor: UIColor.blue
        ] as [NSAttributedString.Key : Any]

        let marketingAttributes = [
            .font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
            .foregroundColor: UIColor.black
        ] as [NSAttributedString.Key : Any]

        let attributedStringComponents = [
            "pay for",
            NSAttributedString(string: "one",
                               attributes: marketingAttributes),
            "and get",
            "three!\n".toAttributed(with: marketingAttributes),
            "Only today!".toAttributed(with: [
                .font: UIFont.systemFont(ofSize: 16.0, weight: .bold),
                .foregroundColor: UIColor.red
            ])
        ] as [AttributedStringComponent]
        label.attributedText = NSAttributedString(from: attributedStringComponents, defaultAttributes: defaultAttributes)
        label.textAlignment = .center
    }
}

결과

여기에 이미지 설명 입력

iOS에서 Attributed String에 접근하는 가장 좋은 방법은 인터페이스 빌더에 내장된 Attributed Text Editor를 사용하여 소스 파일에서 불필요한 NSAtrribed StringKeys 하드코딩을 피하는 것입니다.

나중에 이 확장을 사용하여 실행 시 플레이스호들(Placehodel)을 동적으로 대체할 수 있습니다.

extension NSAttributedString {
    func replacing(placeholder:String, with valueString:String) -> NSAttributedString {

        if let range = self.string.range(of:placeholder) {
            let nsRange = NSRange(range,in:valueString)
            let mutableText = NSMutableAttributedString(attributedString: self)
            mutableText.replaceCharacters(in: nsRange, with: valueString)
            return mutableText as NSAttributedString
        }
        return self
    }
}

다음과 같은 속성 텍스트가 있는 스토리보드 레이블을 추가합니다.

여기에 이미지 설명 입력

그런 다음 필요할 때마다 다음과 같이 값을 업데이트합니다.

label.attributedText = initalAttributedString.replacing(placeholder: "<price>", with: newValue)

원래 값을 initalAttributedString에 저장해야 합니다.

이 접근법에 대해서는, 다음의 기사를 참조해 주세요.https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e

Swift 2.0

다음은 샘플입니다.

let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString

스위프트 5.x

let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString

또는

let stringAttributes = [
    NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 17.0)!,
    NSUnderlineStyleAttributeName : 1,
    NSForegroundColorAttributeName : UIColor.orangeColor(),
    NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
    NSStrokeWidthAttributeName : 2.0]
let atrributedString = NSAttributedString(string: "Sample String: Attributed", attributes: stringAttributes)
sampleLabel.attributedText = atrributedString

당신의 문제를 해결할 온라인 도구를 만들었습니다!문자열을 쓰고 스타일을 적용할 수 있습니다.또한 이 도구는 해당 문자열을 생성하기 위한 objective-c 코드와 swift 코드를 제공합니다.

또한 오픈 소스이므로 자유롭게 연장하여 PR을 보내주시기 바랍니다.

트랜스포머 툴

깃헙

여기에 이미지 설명 입력

베타 6에서 올바르게 동작

let attrString = NSAttributedString(
    string: "title-title-title",
    attributes: NSDictionary(
       object: NSFont(name: "Arial", size: 12.0), 
       forKey: NSFontAttributeName))

Swift 5 이상

   let attributedString = NSAttributedString(string:"targetString",
                                   attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
                                               NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0) as Any])
func decorateText(sub:String, des:String)->NSAttributedString{
    let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.darkText, NSAttributedStringKey.font: UIFont(name: "PTSans-Bold", size: 17.0)!]
    let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont(name: "PTSans-Regular", size: 14.0)!]

    let textPartOne = NSMutableAttributedString(string: sub, attributes: textAttributesOne)
    let textPartTwo = NSMutableAttributedString(string: des, attributes: textAttributesTwo)

    let textCombination = NSMutableAttributedString()
    textCombination.append(textPartOne)
    textCombination.append(textPartTwo)
    return textCombination
}

//실장

cell.lblFrom.attributedText = decorateText(sub: sender!, des: " - \(convertDateFormatShort3(myDateString: datetime!))")

스위프트 4

let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]

let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

swift 4에서 원시 값을 제거해야 합니다.

이 샘플 코드를 사용합니다.이것은 고객의 요건을 충족시키기 위한 매우 짧은 코드입니다.이건 나한테 효과가 있어.

let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]

let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

스위프트 3,4,5

텍스트 색상, 글꼴, 배경 색상 및 밑줄/줄 바꿈 색상에 다음 코드를 사용합니다.

    let text = "swift is language"
    let attributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.backgroundColor: UIColor.blue,NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25.0),NSAttributedString.Key.underlineColor: UIColor.white,NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue] as [NSAttributedString.Key : Any]
        
    let textAttribute = NSAttributedString(string: text, attributes: attributes)
    swiftLabel1.attributedText = textAttribute

여기에 이미지 설명 입력

위의 솔루션은 특정 색상이나 속성을 설정할 때 작동하지 않았습니다.

이 방법은 성공했습니다.

let attributes = [
    NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 12.0)!,
    NSUnderlineStyleAttributeName : 1,
    NSForegroundColorAttributeName : UIColor.darkGrayColor(),
    NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
    NSStrokeWidthAttributeName : 3.0]

var atriString = NSAttributedString(string: "My Attributed String", attributes: attributes)

Swift 2.1 - Xcode 7

let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :[String:AnyObject] = [NSFontAttributeName : labelFont!]
let attrString = NSAttributedString(string:"foo", attributes: attributes)
myLabel.attributedText = attrString

문자열 배열을 취해서 당신이 준 속성으로 속성 문자열을 반환하는 함수를 실행했습니다.

func createAttributedString(stringArray: [String], attributedPart: Int, attributes: [NSAttributedString.Key: Any]) -> NSMutableAttributedString? {
    let finalString = NSMutableAttributedString()
    for i in 0 ..< stringArray.count {
        var attributedString = NSMutableAttributedString(string: stringArray[i], attributes: nil)
        if i == attributedPart {
            attributedString = NSMutableAttributedString(string: attributedString.string, attributes: attributes)
            finalString.append(attributedString)
        } else {
            finalString.append(attributedString)
        }
    }
    return finalString
}

위의 예에서는 attributedPart: Int를 사용하여 속성을 부여할 문자열 부분을 지정합니다.

그런 다음 [NSattributedString]속성과 함께 속성을 지정합니다.키: 임의]

사용 예

if let attributedString = createAttributedString(stringArray: ["Hello ", "how ", " are you?"], attributedPart: 2, attributes: [NSAttributedString.Key.foregroundColor: UIColor.systemYellow]) {
      myLabel.attributedText = attributedString
}

실행 내용:

extension UILabel{
    func setSubTextColor(pSubString : String, pColor : UIColor){    
        let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);

        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString
    }
}

속성은 swift 3에서 직접 설정할 수 있습니다.

    let attributes = NSAttributedString(string: "String", attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 30)!,
         NSForegroundColorAttributeName : UIColor .white,
         NSTextEffectAttributeName : NSTextEffectLetterpressStyle])

그런 다음 속성을 가진 모든 클래스의 변수를 사용합니다.

스위프트 4.2

extension UILabel {

    func boldSubstring(_ substr: String) {
        guard substr.isEmpty == false,
            let text = attributedText,
            let range = text.string.range(of: substr, options: .caseInsensitive) else {
                return
        }
        let attr = NSMutableAttributedString(attributedString: text)
        let start = text.string.distance(from: text.string.startIndex, to: range.lowerBound)
        let length = text.string.distance(from: range.lowerBound, to: range.upperBound)
        attr.addAttributes([NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: self.font.pointSize)],
                           range: NSMakeRange(start, length))
        attributedText = attr
    }
}

제가 만든 라이브러리로 당신의 문제를 해결하는 것은 정말 쉬울 것입니다.그것은 아티부티카라고 불린다.

let calculatedCoffee: Int = 768
let g = Style("g").font(.boldSystemFont(ofSize: 12)).foregroundColor(.red)
let all = Style.font(.systemFont(ofSize: 12))

let str = "\(calculatedCoffee)<g>g</g>".style(tags: g)
    .styleAll(all)
    .attributedString

label.attributedText = str

768g

https://github.com/psharanda/Atributika 에서 찾을 수 있습니다.

 let attrString = NSAttributedString (
            string: "title-title-title",
            attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])

스위프터 스위프트는 일을 하지 않고도 이 일을 할 수 있는 꽤 좋은 방법을 가지고 있다.일치해야 할 패턴과 그에 적용할 속성을 제공하기만 하면 됩니다.그들은 많은 것을 확인할 수 있습니다.

``` Swift
let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
``

이 작업을 적용할 장소가 여러 개 있고 특정 인스턴스에 대해서만 수행하려는 경우 이 방법은 작동하지 않습니다.

이 작업은 한 번에 수행할 수 있습니다. 분리하면 읽기 쉬워집니다.

스위프트 4.x

let attr = [NSForegroundColorAttributeName:self.configuration.settingsColor, NSFontAttributeName: self.configuration.settingsFont]

let title = NSAttributedString(string: self.configuration.settingsTitle,
                               attributes: attr)

Swift 3.0 // 속성 문자열 생성

다음과 같은 속성을 정의합니다.

let attributes = [NSAttributedStringKey.font : UIFont.init(name: "Avenir-Medium", size: 13.0)]

Prestyler 사용을 검토하십시오.

import Prestyler
...
Prestyle.defineRule("$", UIColor.red)
label.attributedText = "\(calculatedCoffee) $g$".prestyled()

Objective-C 2.0의 예:

myUILabel.text = @"€ 60,00";
NSMutableAttributedString *amountText = [[NSMutableAttributedString alloc] initWithString:myUILabel.text];

//Add attributes you are looking for
NSDictionary *dictionaryOfAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [UIFont systemFontOfSize:12],NSFontAttributeName,
                                        [UIColor grayColor],NSForegroundColorAttributeName,
                                        nil];

//Will gray color and resize the € symbol
[amountText setAttributes:dictionaryOfAttributes range:NSMakeRange(0, 1)];
myUILabel.attributedText = amountText;

언급URL : https://stackoverflow.com/questions/24666515/how-do-i-make-an-attributed-string-using-swift