How do I make an attributed string using Swift?

前端 未结 28 1716
耶瑟儿~
耶瑟儿~ 2020-11-22 10:11

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 usin

相关标签:
28条回答
  • 2020-11-22 10:54

    Xcode 6 version:

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

    Xcode 9.3 version:

    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])
    
    0 讨论(0)
  • 2020-11-22 10:54
    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
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:55

    Swift 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
    

    0 讨论(0)
  • 2020-11-22 10:56

    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.

    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.

    You can better understand this approach by reading this article: https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e

    0 讨论(0)
  • 2020-11-22 10:56

    Works well in beta 6

    let attrString = NSAttributedString(
        string: "title-title-title",
        attributes: NSDictionary(
           object: NSFont(name: "Arial", size: 12.0), 
           forKey: NSFontAttributeName))
    
    0 讨论(0)
  • 2020-11-22 10:57

    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

    If you wanted to make a string with four different colors and different fonts using 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

    0 讨论(0)
提交回复
热议问题