jjzjj

ios 11 attributedString 不适用于粗体文本

coder 2024-01-22 原文

我必须在数据库中保存 htmlstring,它可能是粗体、斜体或下划线。 我正在使用下面的代码来获取我将保存在数据库中的字符串。当我将这个保存的字符串从 DB 获取到我的 IOS 10 时,它工作正常,但在 ios 11 的情况下。我的文本没有设置以前保存在 DB 中的样式(没有粗体或斜体等),但相同的文本工作在 IOS 10 上。

func htmlString() -> String? {
    let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do {
      let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
      if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
        return htmlString
      }
    }
    catch {}
    return nil
  }
}

最佳答案

我使用以下扩展函数将 HTML html String 自定义为 NSAttributedString,它在 iOS 10 和 11 (Swift 3.2) 上运行良好

在您的选项中也包括字符编码:

[NSCharacterEncodingDocumentAttribute : encoding.rawValue]

额外的好处 - 我发现设置 HTML 文本的样式很有用 - 如果您想更改字体和颜色,您可以发挥创意并对其进行更多自定义。

extension String {
    public func htmlAttributedString(regularFont: UIFont, boldFont: UIFont, color: UIColor) -> NSAttributedString {
        let encoding = String.Encoding.utf8
        guard let descriptionData = data(using: encoding) else {
            return NSAttributedString()
        }
        let options: [String : Any] = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : encoding.rawValue]
        guard let attributedString = try? NSMutableAttributedString(data: descriptionData, options: options, documentAttributes: nil) else {
            return NSAttributedString()
        }

        let fullRange = NSMakeRange(0, attributedString.length)

        var regularRanges: [NSRange] = []
        var boldRanges: [NSRange] = []

        attributedString.beginEditing()
        attributedString.enumerateAttribute(NSFontAttributeName, in: fullRange, options: .longestEffectiveRangeNotRequired) { (value, range, stop) in
            guard let font = value as? UIFont else {
                return
            }
            if font.fontDescriptor.symbolicTraits.contains(.traitBold) {
                boldRanges.append(range)
            } else {
                regularRanges.append(range)
            }
        }

        for range in regularRanges {
            attributedString.addAttribute(NSFontAttributeName, value: regularFont, range: range)
        }

        for range in boldRanges {
            attributedString.addAttribute(NSFontAttributeName, value: boldFont, range: range)
        }

        attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: fullRange)

        attributedString.endEditing()

        return attributedString
    }
}

关于ios 11 attributedString 不适用于粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093830/

有关ios 11 attributedString 不适用于粗体文本的更多相关文章

  1. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. Ruby Sinatra 配置用于生产和开发 - 2

    我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm

  4. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  5. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  6. ruby - inverse_of 是否适用于 has_many? - 2

    当我使用has_one时,它​​工作得很好,但在has_many上却不行。在这里您可以看到object_id不同,因为它运行了另一个SQL来再次获取它。ruby-1.9.2-p290:001>e=Employee.create(name:'rafael',active:false)ruby-1.9.2-p290:002>b=Badge.create(number:1,employee:e)ruby-1.9.2-p290:003>a=Address.create(street:"123MarketSt",city:"SanDiego",employee:e)ruby-1.9.2-p290

  7. ruby - 安装libv8(3.11.8.13)出错,Bundler无法继续 - 2

    运行bundleinstall后出现此错误:Gem::Package::FormatError:nometadatafoundin/Users/jeanosorio/.rvm/gems/ruby-1.9.3-p286/cache/libv8-3.11.8.13-x86_64-darwin-12.gemAnerroroccurredwhileinstallinglibv8(3.11.8.13),andBundlercannotcontinue.Makesurethat`geminstalllibv8-v'3.11.8.13'`succeedsbeforebundling.我试试gemin

  8. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  9. ruby - "undefined method"用于 rails 模型 - 2

    我正在使用带有Rails的Devise,我想添加一个方法“getAllComments”,所以我这样写:classUser在我的Controller中:defdashboard@user=current_user@comments=@user.getAllComments();end当我访问我的url时,我得到了undefinedmethod`getAllComments'for#我做错了什么?谢谢 最佳答案 因为getAllComments是一个类方法,而您正试图将其作为实例方法访问。您要么需要访问它:User.getAllCom

  10. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

随机推荐