简体   繁体   English

如何使用 Swift 创建属性字符串?

[英]How do I make an attributed string using Swift?

I am trying to make a simple Coffee Calculator.我正在尝试制作一个简单的咖啡计算器。 I need to display the amount of coffee in grams.我需要以克为单位显示咖啡的量。 The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount.克的“g”符号需要附加到我用来显示金额的 UILabel 上。 The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the updating numbers. UILabel 中的数字随着用户输入而动态变化,但我需要在字符串末尾添加一个小写“g”,其格式与更新数字不同。 The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. “g”需要附加到数字上,以便随着数字大小和位置的变化,“g”随着数字“移动”。 I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.我确信这个问题之前已经解决了,所以一个正确方向的链接会很有帮助,因为我已经用谷歌搜索了我的小心脏。

I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift.我在文档中搜索了一个属性字符串,甚至从应用商店下载了一个“属性字符串创建器”,但生成的代码在 Objective-C 中,我使用的是 Swift。 What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift.很棒的,并且可能对其他学习这种语言的开发人员有帮助的,是在 Swift 中使用属性字符串创建具有自定义属性的自定义字体的一个明显示例。 The documentation for this is very confusing as there is not a very clear path on how to do so.这方面的文档非常令人困惑,因为没有关于如何做到这一点的非常明确的路径。 My plan is to create the attributed string and add it to the end of my coffeeAmount string.我的计划是创建属性字符串并将其添加到我的 coffeeAmount 字符串的末尾。

var coffeeAmount: String = calculatedCoffee + attributedText

Where calculatedCoffee is an Int converted to a string and "attributedText" is the lowercase "g" with customized font that I am trying to create.其中 computedCoffee 是一个转换为字符串的 Int,而“attributedText”是小写的“g”,带有我正在尝试创建的自定义字体。 Maybe I'm going about this the wrong way.也许我会以错误的方式解决这个问题。 Any help is appreciated!任何帮助表示赞赏!

在此处输入图像描述

This answer has been updated for Swift 4.2.此答案已针对 Swift 4.2 进行了更新。

Quick Reference快速参考

The general form for making and setting an attributed string is like this.制作和设置属性字符串的一般形式是这样的。 You can find other common options below.您可以在下面找到其他常见选项。

// 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 ]

The rest of this post gives more detail for those who are interested.这篇文章的其余部分为感兴趣的人提供了更多细节。


Attributes属性

String attributes are just a dictionary in the form of [NSAttributedString.Key: Any] , where NSAttributedString.Key is the key name of the attribute and Any is the value of some Type.字符串属性只是[NSAttributedString.Key: Any]形式的字典,其中NSAttributedString.Key是属性的键名, Any是某个类型的值。 The value could be a font, a color, an integer, or something else.该值可以是字体、颜色、整数或其他内容。 There are many standard attributes in Swift that have already been predefined. Swift 中有许多已经预定义的标准属性。 For example:例如:

  • key name: NSAttributedString.Key.font , value: a UIFont键名: NSAttributedString.Key.font ,值: UIFont
  • key name: NSAttributedString.Key.foregroundColor , value: a UIColor键名: NSAttributedString.Key.foregroundColor ,值: UIColor
  • key name: NSAttributedString.Key.link , value: an NSURL or NSString键名: NSAttributedString.Key.link ,值: NSURLNSString

There are many others.还有很多其他的。 See this link for more.有关更多信息,请参阅此链接 You can even make your own custom attributes like:您甚至可以制作自己的自定义属性,例如:

  • key name: NSAttributedString.Key.myName , value: some Type.键名: NSAttributedString.Key.myName ,值:一些类型。
    if you make an extension :如果您进行扩展

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

Creating attributes in Swift在 Swift 中创建属性

You can declare attributes just like declaring any other dictionary.您可以像声明任何其他字典一样声明属性。

// 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" ]

Note the rawValue that was needed for the underline style value.请注意下划线样式值所需的rawValue

Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it.因为属性只是字典,您也可以通过创建一个空字典然后向其中添加键值对来创建它们。 If the value will contain multiple types, then you have to use Any as the type.如果该值将包含多种类型,那么您必须使用Any作为类型。 Here is the multipleAttributes example from above, recreated in this fashion:这是上面的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 Strings属性字符串

Now that you understand attributes, you can make attributed strings.现在您了解了属性,您可以制作属性字符串。

Initialization初始化

There are a few ways to create attributed strings.有几种方法可以创建属性字符串。 If you just need a read-only string you can use NSAttributedString .如果你只需要一个只读字符串,你可以使用NSAttributedString Here are some ways to initialize it:以下是一些初始化它的方法:

// 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)

If you will need to change the attributes or the string content later, you should use NSMutableAttributedString .如果您稍后需要更改属性或字符串内容,则应使用NSMutableAttributedString The declarations are very similar:声明非常相似:

// 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)

Changing an Attributed String更改属性字符串

As an example, let's create the attributed string at the top of this post.例如,让我们在这篇文章的顶部创建属性字符串。

First create an NSMutableAttributedString with a new font attribute.首先创建一个带有新字体属性的NSMutableAttributedString

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

If you are working along, set the attributed string to a UITextView (or UILabel ) like this:如果您正在工作,请将属性字符串设置为UITextView (或UILabel ),如下所示:

textView.attributedText = myString

You don't use textView.text .使用textView.text

Here is the result:结果如下:

在此处输入图像描述

Then append another attributed string that doesn't have any attributes set.然后附加另一个没有设置任何属性的属性字符串。 (Notice that even though I used let to declare myString above, I can still modify it because it is an NSMutableAttributedString . This seems rather unSwiftlike to me and I wouldn't be surprised if this changes in the future. Leave me a comment when that happens.) (请注意,即使我在上面使用let声明myString ,我仍然可以修改它,因为它是一个NSMutableAttributedString 。这对我来说似乎很不像Swift,如果将来发生这种变化,我不会感到惊讶。当那个时候给我留言发生。)

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

在此处输入图像描述

Next we'll just select the "Strings" word, which starts at index 17 and has a length of 7 .接下来,我们将只选择“字符串”这个词,它从索引17开始,长度为7 Notice that this is an NSRange and not a Swift Range .请注意,这是一个NSRange而不是 Swift Range (See this answer for more about Ranges.) The addAttribute method lets us put the attribute key name in the first spot, the attribute value in the second spot, and the range in the third spot. (有关 Ranges 的更多信息,请参阅此答案。) addAttribute方法允许我们将属性键名称放在第一个位置,将属性值放在第二个位置,将范围放在第三个位置。

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)

在此处输入图像描述

Finally, let's add a background color.最后,让我们添加背景颜色。 For variety, let's use the addAttributes method (note the s ).对于多样性,让我们使用addAttributes方法(注意s )。 I could add multiple attributes at once with this method, but I will just add one again.我可以使用此方法一次添加多个属性,但我将再次添加一个。

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

在此处输入图像描述

Notice that the attributes are overlapping in some places.请注意,属性在某些地方是重叠的。 Adding an attribute doesn't overwrite an attribute that is already there.添加属性不会覆盖已经存在的属性。

Related有关的

Further Reading延伸阅读

Swift uses the same NSMutableAttributedString that Obj-C does. Swift 使用与 Obj-C 相同的NSMutableAttributedString You instantiate it by passing in the calculated value as a string:您通过将计算值作为字符串传递来实例化它:

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

Now create the attributed g string (heh).现在创建属性g字符串 (heh)。 Note: UIFont.systemFontOfSize(_) is now a failable initializer, so it has to be unwrapped before you can use it:注意: UIFont.systemFontOfSize(_)现在是一个可失败的初始化程序,因此必须先将其解包,然后才能使用它:

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

And then append it:然后附加它:

attributedString.appendAttributedString(gString)

You can then set the UILabel to display the NSAttributedString like this:然后,您可以将 UILabel 设置为显示 NSAttributedString,如下所示:

myLabel.attributedText = attributedString

Xcode 6 version : Xcode 6 版本

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

Xcode 9.3 version : Xcode 9.3 版本

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

Xcode 10, iOS 12, Swift 4 : Xcode 10、iOS 12、Swift 4

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

I would highly recommend using a library for attributed strings.我强烈建议使用属性字符串库。 It makes it much easier when you want, for example, one string with four different colors and four different fonts.例如,当您需要一个具有四种不同颜色和四种不同字体的字符串时,它会变得更加容易。 Here is my favorite.这是我最喜欢的。 It is called SwiftyAttributes它被称为 SwiftyAttributes

If you wanted to make a string with four different colors and different fonts using SwiftyAttributes:如果您想使用 SwiftyAttributes 制作具有四种不同颜色和不同字体的字符串:

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 would show as finalString将显示为

显示为图像

Swift 4:斯威夫特 4:

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

Swift 5斯威夫特 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: xcode 6.1斯威夫特:xcode 6.1

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

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

Details细节

  • Swift 5.2, Xcode 11.4 (11E146)斯威夫特 5.2、Xcode 11.4 (11E146)

Solution解决方案

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

Usage用法

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)

Full Example完整示例

do not forget to paste the solution code here不要忘记在此处粘贴解决方案代码

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

Result结果

在此处输入图像描述

The best way to approach Attributed Strings on iOS is by using the built-in Attributed Text editor in the interface builder and avoid uneccessary hardcoding NSAtrributedStringKeys in your source files.在 iOS 上处理属性字符串的最佳方法是使用界面构建器中的内置属性文本编辑器,并避免在源文件中对 NSAtrributedStringKeys 进行不必要的硬编码。

You can later dynamically replace placehoderls at runtime by using this extension:您可以稍后使用此扩展在运行时动态替换占位符:

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

Add a storyboard label with attributed text looking like this.添加一个带有属性文本的故事板标签,如下所示。

在此处输入图像描述

Then you simply update the value each time you need like this:然后,您只需在每次需要时更新值,如下所示:

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

Make sure to save into initalAttributedString the original value.确保将原始值保存到 initalAttributedString 中。

You can better understand this approach by reading this article: https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e您可以通过阅读本文更好地理解这种方法: https ://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e

Swift 2.0斯威夫特 2.0

Here is a sample:这是一个示例:

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

Swift 5.x斯威夫特 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

OR或者

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

I created an online tool that is going to solve your problem!我创建了一个在线工具来解决您的问题! You can write your string and apply styles graphically and the tool gives you objective-c and swift code to generate that string.您可以编写字符串并以图形方式应用样式,该工具为您提供 Objective-c 和 swift 代码来生成该字符串。

Also is open source so feel free to extend it and send PRs.也是开源的,所以请随意扩展它并发送 PR。

Transformer Tool变压器工具

Github Github

在此处输入图像描述

Works well in beta 6在 beta 6 中运行良好

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

Swift 5 and above斯威夫特 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
}

//Implementation //执行

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

Swift 4斯威夫特 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)

You need to remove the raw value in swift 4您需要在 swift 4 中删除原始值

Use this sample code.使用此示例代码。 This is very short code to achieve your requirement.这是满足您要求的非常短的代码。 This is working for me.这对我有用。

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)

For me above solutions didn't work when setting a specific color or property.对我来说,上述解决方案在设置特定颜色或属性时不起作用。

This did work:这确实有效:

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斯威夫特 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

I did a function that takes array of strings and returns attributed string with the attributes you give.我做了一个函数,它接受字符串数组并返回带有您提供的属性的属性字符串

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
}

In the example above you specify what part of string you want to get attributed with attributedPart: Int在上面的示例中,您指定要使用属性部分属性的字符串的哪一部分: Int

And then you give the attributes for it with attributes: [NSAttributedString.Key: Any]然后你用属性给它的属性: [NSAttributedString.Key: Any]

USE EXAMPLE使用示例

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

Will do:会做:

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

The attributes can be setting directly in swift 3...属性可以直接在swift 3中设置...

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

Then use the variable in any class with attributes然后在任何具有属性的类中使用该变量

Swift 4.2斯威夫特 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 attrString = NSAttributedString (
            string: "title-title-title",
            attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])

It will be really easy to solve your problem with the library I created.使用我创建的库解决您的问题将非常容易。 It is called Atributika.它被称为属性。

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

768克

You can find it here https://github.com/psharanda/Atributika你可以在这里找到它https://github.com/psharanda/Atributika

Swifter Swift has a pretty sweet way to do this without any work really. Swifter Swift有一个非常好的方法来做到这一点,而无需任何工作。 Just provide the pattern that should be matched and what attributes to apply to it.只需提供应该匹配的模式以及应用到它的属性。 They're great for a lot of things check them out.它们对很多事情都很棒,请检查一下。

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

If you have multiple places where this would be applied and you only want it to happen for specific instances then this method wouldn't work.如果您有多个地方可以应用此方法并且您只希望它发生在特定实例中,那么此方法将不起作用。

You can do this in one step, just easier to read when separated.您可以一步完成,分开时更容易阅读。

Swift 3,4,5斯威夫特 3,4,5

Use below code for Text Color, Font, Background Color and Underline/Un derline Color将以下代码用于文本颜色、字体、背景颜色和下划线/下划线颜色

    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

在此处输入图像描述

Swift 4.x斯威夫特 4.x

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

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

Swift 3.0 // create attributed string Swift 3.0 // 创建属性字符串

Define attributes like定义属性如

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

Please consider using Prestyler请考虑使用Prestyler

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

Objective-C 2.0 example: 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;
extension String {
//MARK: Getting customized string
struct StringAttribute {
    var fontName = "HelveticaNeue-Bold"
    var fontSize: CGFloat?
    var initialIndexOftheText = 0
    var lastIndexOftheText: Int?
    var textColor: UIColor = .black
    var backGroundColor: UIColor = .clear
    var underLineStyle: NSUnderlineStyle = .styleNone
    var textShadow: TextShadow = TextShadow()

    var fontOfText: UIFont {
        if let font = UIFont(name: fontName, size: fontSize!) {
            return font
        } else {
            return UIFont(name: "HelveticaNeue-Bold", size: fontSize!)!
        }
    }

    struct TextShadow {
        var shadowBlurRadius = 0
        var shadowOffsetSize = CGSize(width: 0, height: 0)
        var shadowColor: UIColor = .clear
    }
}
func getFontifiedText(partOfTheStringNeedToConvert partTexts: [StringAttribute]) -> NSAttributedString {
    let fontChangedtext = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: (partTexts.first?.fontSize)!)!])
    for eachPartText in partTexts {
        let lastIndex = eachPartText.lastIndexOftheText ?? self.count
        let attrs = [NSFontAttributeName : eachPartText.fontOfText, NSForegroundColorAttributeName: eachPartText.textColor, NSBackgroundColorAttributeName: eachPartText.backGroundColor, NSUnderlineStyleAttributeName: eachPartText.underLineStyle, NSShadowAttributeName: eachPartText.textShadow ] as [String : Any]
        let range = NSRange(location: eachPartText.initialIndexOftheText, length: lastIndex - eachPartText.initialIndexOftheText)
        fontChangedtext.addAttributes(attrs, range: range)
    }
    return fontChangedtext
}

} }

//Use it like below //像下面这样使用

    let someAttributedText = "Some   Text".getFontifiedText(partOfTheStringNeedToConvert: <#T##[String.StringAttribute]#>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM