How do I make an attributed string using Swift?

前端 未结 28 2410
耶瑟儿~
耶瑟儿~ 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条回答
  •  猫巷女王i
    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]#>)
    

提交回复
热议问题