【问题标题】:How do I make an attributed string using Swift?如何使用 Swift 创建属性字符串?
【发布时间】:2014-08-31 05:40:34
【问题描述】:

我正在尝试制作一个简单的咖啡计算器。我需要以克为单位显示咖啡的量。克的“g”符号需要附加到我用来显示金额的 UILabel 上。 UILabel 中的数字随着用户输入而动态变化,但我需要在字符串末尾添加一个小写“g”,其格式与更新数字不同。 “g”需要附加到数字上,以便随着数字大小和位置的变化,“g”随着数字“移动”。我确信这个问题之前已经解决了,所以一个正确方向的链接会很有帮助,因为我已经用谷歌搜索了我的小心脏。

我在文档中搜索了一个属性字符串,甚至从应用商店下载了一个“属性字符串创建器”,但生成的代码在 Objective-C 中,我使用的是 Swift。很棒的,并且可能对其他学习这种语言的开发人员有帮助的,是在 Swift 中使用属性字符串创建具有自定义属性的自定义字体的一个明显示例。这方面的文档非常令人困惑,因为没有关于如何做到这一点的非常明确的路径。我的计划是创建属性字符串并将其添加到我的 coffeeAmount 字符串的末尾。

var coffeeAmount: String = calculatedCoffee + attributedText

其中 computedCoffee 是一个转换为字符串的 Int,“attributedText”是小写的“g”,带有我正在尝试创建的自定义字体。也许我会以错误的方式解决这个问题。任何帮助表示赞赏!

【问题讨论】:

    标签: fonts uilabel swift nsattributedstring


    【解决方案1】:

    Swift 使用与 Obj-C 相同的 NSMutableAttributedString。您可以通过将计算值作为字符串传递来实例化它:

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

    现在创建属性g 字符串(呵呵)。 注意: UIFont.systemFontOfSize(_) 现在是一个可失败的初始化程序,因此必须先解包,然后才能使用它:

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

    然后追加:

    attributedString.appendAttributedString(gString)
    

    然后您可以像这样设置 UILabel 以显示 NSAttributedString:

    myLabel.attributedText = attributedString
    

    【讨论】:

    • //Part 1 Set Up The Lower Case g var coffeeText = NSMutableAttributedString(string:"\(calculateCoffee())") //Part 2 set the font attributes for the lower case g var coffeeTypeFaceAttributes = [NSFontAttributeName : UIFont.systemFontOfSize(18)] //Part 3 create the "g" character and give it the attributes var coffeeG = NSMutableAttributedString(string:"g", attributes:coffeeTypeFaceAttributes) 当我设置我的 UILabel.text = coffeeText 时,我收到一个错误“NSMutableAttributedString 不能转换为'String'。有没有办法让 UILabel 接受 NSMutableAttributedString?
    • 当你有一个属性字符串时,你需要设置标签的属性文本属性而不是它的文本属性。
    • 这工作正常,我的小写“g”现在附加到我的咖啡量文本的末尾
    • 由于某种原因,我在使用 NSAttributedString 的行上收到错误“调用中的额外参数”。这只发生在我将 UIFont.systemFontOfSize(18) 切换到 UIFont(name: "Arial", size: 20) 时。有什么想法吗?
    • UIFont(name: size:) 是一个失败的初始化器,可能返回 nil。您可以通过添加显式打开它!最后或在将其插入字典之前使用 if/let 语句将其绑定到变量。
    【解决方案2】:

    在 beta 6 中运行良好

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        斯威夫特:xcode 6.1

            let font:UIFont? = UIFont(name: "Arial", size: 12.0)
        
            let attrString = NSAttributedString(
                string: titleData,
                attributes: NSDictionary(
                    object: font!,
                    forKey: NSFontAttributeName))
        

        【讨论】:

          【解决方案5】:
           let attrString = NSAttributedString (
                      string: "title-title-title",
                      attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
          

          【讨论】:

            【解决方案6】:

            对我来说,上述解决方案在设置特定颜色或属性时不起作用。

            这确实有效:

            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)
            

            【讨论】:

              【解决方案7】:

              此答案已针对 Swift 4.2 进行了更新。

              快速参考

              制作和设置属性字符串的一般形式是这样的。您可以在下面找到其他常用选项。

              // 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]形式的字典,其中NSAttributedString.Key是属性的键名,Any是某个Type的值。该值可以是字体、颜色、整数或其他内容。 Swift 中有许多已经预定义的标准属性。例如:

              • 键名:NSAttributedString.Key.font,值:aUIFont
              • 键名:NSAttributedString.Key.foregroundColor,值:aUIColor
              • 键名:NSAttributedString.Key.link,值:NSURLNSString

              还有很多其他的。有关更多信息,请参阅this link。您甚至可以制作自己的自定义属性,例如:

              • 键名:NSAttributedString.Key.myName,值:一些类型。
                如果你发extension:

                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

              因为属性只是字典,您也可以通过创建一个空字典然后向其中添加键值对来创建它们。如果该值将包含多种类型,那么您必须使用Any 作为类型。这是上面的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
              

              属性字符串

              既然您了解了属性,您就可以制作属性字符串了。

              初始化

              有几种方法可以创建属性字符串。如果你只需要一个只读字符串,你可以使用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)
              

              更改属性字符串

              例如,让我们在这篇文章的顶部创建属性字符串。

              首先创建一个带有新字体属性的NSMutableAttributedString

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

              如果您正在使用,请将属性字符串设置为 UITextView(或 UILabel),如下所示:

              textView.attributedText = myString
              

              不要使用textView.text

              结果如下:

              然后附加另一个没有设置任何属性的属性字符串。 (请注意,即使我在上面使用let 声明myString,我仍然可以修改它,因为它是NSMutableAttributedString。这对我来说似乎很不Swift,如果将来这种情况发生变化,我不会感到惊讶。发生这种情况时给我留言。)

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

              接下来我们将只选择“字符串”字,它从索引17 开始,长度为7。请注意,这是 NSRange 而不是 Swift Range。 (有关 Ranges 的更多信息,请参阅 this answer。)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)
              

              最后,让我们添加背景颜色。对于多样性,让我们使用addAttributes 方法(注意s)。我可以使用这种方法一次添加多个属性,但我只会添加一个。

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

              请注意,属性在某些地方是重叠的。添加属性不会覆盖已经存在的属性。

              相关

              进一步阅读

              【讨论】:

              • 请注意,您可以将几种样式组合用于下划线,例如NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue | NSUnderlineStyle.PatternDot.rawValue
              • 你不能在 NSAttributedString 上使用 appendAttributedString,它必须在 NSMutableAttributedString 上,你能更新你的答案来反映这一点吗?
              • 1) 非常感谢您的回答。 2) 我建议您将textView.atrributedtText = myStringmyLabel.attributedText = myString 放在答案的开头。作为一个新手,我只是在做 myLabel.text 并且认为我不需要通过 all 你的答案。**3)** 这是否意味着你只能拥有 attributedTexttext 因为同时拥有它们毫无意义? 4) 我建议您在答案中也加入lineSpacing 示例,例如this,因为它非常 有用。 5) ачаар дахин
              • append 和 add 之间的区别首先令人困惑。 appendAttributedString 就像“字符串连接”。 addAttribute 正在为您的字符串添加一个新属性。
              • @Daniel,addAttributeNSMutableAttributedString 的方法。你是对的,你不能将它与StringNSAttributedString 一起使用。 (检查这篇文章 更改属性字符串 部分中的 myString 定义。我想我把你赶走了,因为我还在文章的第一部分使用了myString 作为变量名,其中这是一个NSAttributedString。)
              【解决方案8】:

              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
              

              【讨论】:

              • Swift 2.0 和 2.1 之间发生了哪些变化?
              【解决方案9】:

              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
              

              Swift 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
              

              【讨论】:

                【解决方案10】:
                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
                    }
                }
                

                【讨论】:

                • cell.IBLabelGuestAppointmentTime.text = "\n\nGuest1\n8:00 am\n\nGuest2\n9:00Am\n\n" cell.IBLabelGuestAppointmentTime.setSubTextColor(pSubString: "Guest1", pColor : UIColor.white) cell.IBLabelGuestAppointmentTime.setSubTextColor(pSubString: "Guest2", pColor: UIColor.red)
                • 欢迎来到 SO。请格式化您的代码,并为您的答案添加一些解释/上下文。见:stackoverflow.com/help/how-to-answer
                【解决方案11】:

                我强烈建议使用属性字符串库。例如,当您需要一个具有四种不同颜色和四种不同字体的字符串时,它会非常 变得更容易。 Here is my favorite. 叫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 将显示为

                【讨论】:

                  【解决方案12】:

                  使用我创建的库可以很容易地解决您的问题。它被称为属性。

                  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
                  

                  你可以在这里找到它https://github.com/psharanda/Atributika

                  【讨论】:

                    【解决方案13】:

                    属性可以直接在swift 3中设置...

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

                    然后在任何具有属性的类中使用该变量

                    【讨论】:

                      【解决方案14】:

                      斯威夫特 4:

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

                      【讨论】:

                      • 无法编译Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'
                      • 我刚刚在最新的 XCode (10 beta 6) 中尝试过它并且可以编译,你确定你使用的是 Swift 4?
                      • 我正在使用 Swift 3
                      • 这就是问题所在,我的答案是粗体标题“Swift 4”,我强烈建议您更新到 Swift 4
                      • @bibscy 你可以使用 NSAttributedString.Key.***
                      【解决方案15】:

                      我创建了一个在线工具来解决您的问题!您可以编写字符串并以图形方式应用样式,该工具会为您提供 Objective-c 和 swift 代码来生成该字符串。

                      也是开源的,所以请随意扩展它并发送 PR。

                      Transformer Tool

                      Github

                      【讨论】:

                      • 不适合我。它只是将所有内容都包含在括号中而不应用任何样式。
                      • 这正是我想要的。!谁还记得NSAttributedString 无论如何? #已收藏
                      【解决方案16】:

                      在 iOS 上处理属性字符串的最佳方法是使用界面构建器中的内置属性文本编辑器,并避免在源文件中对 NSAtrributedStringKeys 进行不必要的硬编码。

                      您可以稍后使用此扩展在运行时动态替换占位符:

                      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

                      【讨论】:

                      • 这对我的案例非常有帮助,我有一个情节提要,只是想在标签中的部分字符串中添加粗体。比手动设置所有属性要简单得多。
                      • 这个扩展曾经对我很有效,但是在 Xcode 11 中它在let nsRange = NSRange(range,in:valueString) 行崩溃了我的应用程序。
                      【解决方案17】:
                      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
                      }
                      

                      }

                      //像下面这样使用它

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

                      【讨论】:

                      • 这个答案告诉你除了如何在 swift 中创建一个属性字符串之外你需要知道的一切。
                      【解决方案18】:
                      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!))")
                      

                      【讨论】:

                        【解决方案19】:

                        斯威夫特 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 中删除原始值

                        【讨论】:

                          【解决方案20】:

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

                          【讨论】:

                          • 为什么不简单地用 range.count 作为长度?
                          【解决方案21】:

                          斯威夫特 4.x

                          let attr = [NSForegroundColorAttributeName:self.configuration.settingsColor, NSFontAttributeName: self.configuration.settingsFont]
                          
                          let title = NSAttributedString(string: self.configuration.settingsTitle,
                                                         attributes: attr)
                          

                          【讨论】:

                            【解决方案22】:

                            斯威夫特 3.0 // 创建属性字符串

                            定义属性如

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

                            【讨论】:

                              【解决方案23】:

                              请考虑使用Prestyler

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

                              【讨论】:

                                【解决方案24】:

                                Swift 5 及以上版本

                                   let attributedString = NSAttributedString(string:"targetString",
                                                                   attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
                                                                               NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0) as Any])
                                

                                【讨论】:

                                  【解决方案25】:

                                  Swifter Swift 有一个非常不错的方法来做到这一点,而无需任何工作。只需提供应该匹配的模式以及应用到它的属性。它们对很多事情都很棒,请检查一下。

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

                                  如果您有多个地方可以应用此方法,并且您只希望它发生在特定实例中,那么此方法将不起作用。

                                  您可以一步完成,分开时更易于阅读。

                                  【讨论】:

                                    【解决方案26】:

                                    使用此示例代码。这是满足您要求的非常短的代码。这对我有用。

                                    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)
                                    

                                    【讨论】:

                                      【解决方案27】:

                                      详情

                                      • Swift 5.2、Xcode 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
                                          }
                                      }
                                      

                                      结果

                                      【讨论】:

                                        【解决方案28】:

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

                                        【讨论】:

                                          【解决方案29】:

                                          我做了一个函数,它接受 字符串数组 并返回 attributed string 以及您提供的属性。

                                          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.Key: Any]

                                          使用示例

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

                                          会做的:

                                          【讨论】:

                                            【解决方案30】:

                                            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;
                                            

                                            【讨论】:

                                              猜你喜欢
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 2014-10-23
                                              • 2015-09-21
                                              相关资源
                                              最近更新 更多