How do I make an attributed string using Swift?

前端 未结 28 1715
耶瑟儿~
耶瑟儿~ 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:50
    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!))")
    
    0 讨论(0)
  • 2020-11-22 10:50

    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
    

    You can find it here https://github.com/psharanda/Atributika

    0 讨论(0)
  • 2020-11-22 10:51
     let attrString = NSAttributedString (
                string: "title-title-title",
                attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
    
    0 讨论(0)
  • 2020-11-22 10:52
    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]#>)
    
    0 讨论(0)
  • 2020-11-22 10:53

    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.

    Also is open source so feel free to extend it and send PRs.

    Transformer Tool

    Github

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

    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)
    
    0 讨论(0)
提交回复
热议问题