如何在Swift 4中将html字符串设置为标签时,如何设置常规字体和粗体字体?

时间:2019-05-20 05:18:48

标签: ios objective-c swift uilabel swift4

我从HTML响应中获得了API格式的字符串,因此我需要将其设置为标签,同时保持自定义字体(自我的应用程序开始)并应用样式(粗体,常规,等)。

我使用了扩展名,可以将HTML字符串转换为带有换行符的常规字符串。但是,我能够在此处设置字体,但是只能设置一种字体,并且只能以常规字体显示,因此整个标签是一种字体,我要设置的是将粗体HTML部分设置为粗体,将常规HTML部分/标记设置为常规。

extension String {
    var htmlToAttributedString: NSAttributedString {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString.string
    }
}

//set converted html to string here
let whyAttendAttributedText: NSMutableAttributedString = NSMutableAttributedString(attributedString: attendData.whyAttendData?.desc?.htmlToAttributedString ?? NSAttributedString())

//set font here   
whyAttendAttributedText.addAttributes([NSMutableAttributedString.Key.font: CommonSettings.shared.getFont(type: .regular, size: descriptionLabel.font.pointSize), NSMutableAttributedString.Key.foregroundColor: UIColor.white], range: NSMakeRange(0, whyAttendAttributedText.length))

我想为文本设置粗体和常规字体,但是由于我只设置了一种字体而无法获得结果,是否有任何办法像HTML字符串中那样设置粗体和常规字体?

3 个答案:

答案 0 :(得分:0)

可以使用以下方法将粗体和其他不同样式应用于文本。

extension String {

    func attributedString(with style: [NSAttributedString.Key: Any]? = nil,
                          and highlightedText: String,
                          with highlightedTextStyle: [NSAttributedString.Key: Any]? = nil) -> NSAttributedString {

        let formattedString = NSMutableAttributedString(string: self, attributes: style)
        let highlightedTextRange: NSRange = (self as NSString).range(of: highlightedText as String)
        formattedString.setAttributes(highlightedTextStyle, range: highlightedTextRange)
        return formattedString
    }
}

输入:“这是一条测试消息”

预期的输出:“这是一条测试消息”

这可以通过以下方式实现。

let sampleInput = "This is a test message"
let boldtext = "test"

let output = sampleInput.attributedString(with: [.font: UIFont.systemFont(ofSize: 12.0, weight: .regular)],
                             and: boldtext, with: UIFont.systemFont(ofSize: 12.0, weight: .bold))

可以使用不同的属性键来应用不同的样式。希望这会有所帮助。

答案 1 :(得分:0)

让我们假设您在解析HTML字符串后的字符串为:"This is your HTML string"

要创建attributed string

let attrStr = NSMutableAttributedString(string: "This is your HTML string")

添加值为UIFont的{​​{1}}属性,

System-Regular

每当将attrStr.addAttribute(.font, value: UIFont.systemFont(ofSize: 14.0, weight: .regular), range: NSRange(location: 0, length: attrStr.length)) 添加到attribute时,我们都需要提供attributed string中的range,以便在其中反映string

由于我们需要整个attribute拥有string字体,因此Regular被计算为整个range string

现在,将length的值为UIFont的{​​{1}}属性添加到System-Bold的一部分中,假设我们将 string 设为粗体,

HTML

我们已经计算出整个字符串中的HTML单词attrStr.addAttribute(.font, value: UIFont.systemFont(ofSize: 14.0, weight: .bold), range: (attrStr.string as NSString).range(of: "HTML"))

类似地,您可以将range中的任何一个添加到attributes中,并提供相关的string值。

输出: range This is your HTML

编辑1:

要计算string中的range,您需要手动计算。

示例:

<b> to </b>

以上示例适用于let str = "This <b>is your HTML</b> string" let range1 = (str as NSString).range(of: "<b>") let range2 = (str as NSString).range(of: "</b>") let requiredRange = NSRange(location: range1.location, length: range2.location + range2.length - range1.location) <b>/</b>的单个实例。

编辑2:

string包含string的多个实例时:

<b>/</b>

输出: let htmlStr = "This is an <b>HTML</b> parsed <b>string</b>" let arr = htmlStr.components(separatedBy: "</b>") let attrStr = NSMutableAttributedString() for str in arr { if !str.isEmpty { let range1 = (str as NSString).range(of: "<b>") let requiredRange = NSRange(location: range1.location, length: str.count - range1.location) let formattedStr = NSMutableAttributedString(string: str) formattedStr.addAttribute(.font, value: UIFont.systemFont(ofSize: 14.0, weight: .bold), range: requiredRange) attrStr.append(formattedStr) attrStr.append(NSAttributedString.init(string: "</b>", attributes: [.font : UIFont.systemFont(ofSize: 14.0, weight: .bold)])) } } self.label.attributedText = attrStr This is an <b>HTML</b> parsed

答案 2 :(得分:0)

这应该有帮助:

extension String {

func attributedString(withRegularFont regularFont: UIFont, andBoldFont boldFont: UIFont) -> NSMutableAttributedString {
    var attributedString = NSMutableAttributedString()
        guard let data = self.data(using: .utf8) else { return NSMutableAttributedString() }
        do {
            attributedString = try NSMutableAttributedString(data: data,
                                                             options: [.documentType: NSAttributedString.DocumentType.html,
                                                                       .characterEncoding:String.Encoding.utf8.rawValue],
                                                             documentAttributes: nil)
            let range = NSRange(location: 0, length: attributedString.length)
            attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in
                let currentFont: UIFont         = value as! UIFont
                var replacementFont: UIFont?    = nil

                if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Bold") {
                    replacementFont             =   boldFont
                } else {
                    replacementFont             =   regularFont
                }

                let replacementAttribute        =   [NSAttributedString.Key.font:replacementFont!]
                attributedString.addAttributes(replacementAttribute, range: range)
            }
        } catch let e {
            print(e.localizedDescription)
        }
       return attributedString
}
}