草庐IT

ios - 由于 NSAttributedString,UITableView 滚动不流畅

coder 2024-01-15 原文

我正在使用 NSAttributedString 将 html 字符串转换为 attributedString。我已经转换了它,但 label 在单元格中,所以我在 cellForRowAtIndex 中编写了下面的代码,当我应用此代码时,tableview 不会平滑滚动。如果我用简单的文本删除它,它会平滑滚动。

 cell.lblDescription.setHTMLFromString(htmlText: model.strItineraryDescription)

我已经将 html string 转换为 attributed string

extension UILabel {

    func setHTMLFromString(htmlText: String) {
        let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(self.font!.pointSize)\">%@</span>" as NSString, htmlText) as String


        //process collection values
        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
            documentAttributes: nil)


        self.attributedText = attrStr
    }

}

我的html字符串

<strong><u>Featured Program</u></strong></p>
\n<ol>
\n  <li>Arrival at Delhi airport. You will receive by our representative.</li>
\n  <li>Driving to Agra and exploring the city.</li>
\n  <li>Back to Hotel for Overnight stay.</li>
\n</ol>
\n<p><strong>City Features</strong></p>
\n<ol>
\n  <li><strong>Visit to Agra Fort \U2013 </strong>Former Name Badalgarh, Shah-Jahan spent his last eight years here. You can watch the mesmerizing view of Taj Mahal from this fort just like Shah Jahan.</li>
\n  <li><strong>Visit to Taj Mahal \U2013</strong> It took 21 years to build and stood in 1653. The palace is considered as the symbol of love. Shah Jahan built this wonder in the memory of his wife Mumtaj Mahal.</li>
\n</ol>
\n<p><strong>(Both Agra Fort and Taj Mahal are UNESCO Declared world heritage site)</strong>

最佳答案

这个 html2AttributedString 有什么作用?它是否在 cellForRowAtIndexPath 上即时将 HTML 转换为属性字符串?如果是,这实际上需要时间。我们能否通过在模型中的另一个变量中缓存 HTML 的等效属性字符串来在内存上做出妥协以加快速度。因此,通过这种方式重新加载时,它将在单元格创建或重用期间获取准备好的属性字符串。

例如,伪代码:

class MyModel
{
    var myHTML: String = ""
    var myHTML2AttributedString: String = ""
}


class ModelMapping
{
  ...
  myModel.myHTML = responseFromJSON["htmlText"]
  myModel.myHTML2AttributedString = customFuncToConvertHTMLToAttributed(myModel.myHTML)
  ...
}

class ViewController
{
  ...
  cell.lblDescription.attributedText = myModel.myHTML2AttributedString // This one would be cached Attributed string equivalent of HTML string.
  ...
}

希望对您有所帮助!

编辑:

class MyModel
{
    var myAttributedHTML: NSMutableAttributedString = ""
    var strItineraryDescription: String = ""

    func prepareHTMLFromString() {
        let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(self.font!.pointSize)\">%@</span>" as NSString, self.strItineraryDescription) as String


        //process collection values
        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
            documentAttributes: nil)


        myAttributedHTML = attrStr.mutableCopy()
    }
}

class MyViewController
{
   ...
   cell.lblDescription.attributedText = myModel.myAttributedHTML
   ...
}

class ResponseHandler
{
   ...
   myModel.strItineraryDescription = responseFromServer["myHTML"]
   myModel.prepareHTMLFromString()
   ...
}

关于ios - 由于 NSAttributedString,UITableView 滚动不流畅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43736150/

有关ios - 由于 NSAttributedString,UITableView 滚动不流畅的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. 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返回它复制的字节数,但是当我还没有下

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

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

  4. 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使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  5. 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上

  6. 由于 libgmp.10.dylib 的问题,Ruby 2.2.0 无法运行 - 2

    我刚刚安装了带有RVM的Ruby2.2.0,并尝试使用它得到了这个:$rvmuse2.2.0--defaultUsing/Users/brandon/.rvm/gems/ruby-2.2.0dyld:Librarynotloaded:/usr/local/lib/libgmp.10.dylibReferencedfrom:/Users/brandon/.rvm/rubies/ruby-2.2.0/bin/rubyReason:Incompatiblelibraryversion:rubyrequiresversion13.0.0orlater,butlibgmp.10.dylibpro

  7. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  8. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

  9. ruby - 由于 GEM_HOME 的要求,启动 Ruby 应用程序非常慢 - 2

    我目前正在开发一个ruby​​应用程序,但它运行得非常(非常!)慢..到目前为止,我已经尝试了几件事,我可以将其缩小到主要问题:Ruby正在尝试在$LOAD_PATH的每个目录中查找它的需求。基本上我所观察到的是,ruby正在查看大量文件,试图查看那里是否存在需求。如果找不到它们,它将转到下一个目录。好消息是我可以通过strace看到这种情况。有很多这样的输出:open("/boa_proj_build/nsteen/.gem/gems/i18n-0.7.0/lib/commander/help_formatters/base.rb",O_RDONLY|O_CLOEXEC)=-1ENO

  10. ruby - 如何使用 ruby​​ fibers 避免阻塞 IO - 2

    我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文

随机推荐