HTML Format in UITextView

前端 未结 8 977
轻奢々
轻奢々 2020-12-01 07:19

i\'m quite new to iOS Development and right now working on an app which receive some kind of JSON Data. But some Backend Experts thought, that it would be better for the Use

相关标签:
8条回答
  • I had an app that had a UITextView where I wanted to be able to paste html formatted text from the browser and then save it as a string(containing html formatting) to the database, and then another time retrieve it from the database and show it with the same format as it was first copied from the website. I managed this by making these two extensions:

    extension String
    {
        func getAttributedStringFromHTMLString() -> NSAttributedString
        {
            do {
                let attributedString = try NSAttributedString(data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
                return attributedString
            } catch {
                print(error)
                return NSAttributedString()
            }
        }
    }
    
    extension NSAttributedString
    {
        func getHTMLString() -> String
        {
            var htmlText = "";
            let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
            do {
                let htmlData = try self.dataFromRange(NSMakeRange(0, self.length), documentAttributes:documentAttributes)
                if let htmlString = String(data:htmlData, encoding:NSUTF8StringEncoding) {
                    htmlText = htmlString
                }
                return htmlText
            }
            catch {
                print("error creating HTML from Attributed String")
                return ""
            }
        }
    }
    
    0 讨论(0)
  • Check the attributes of your UITextView in IB. In order for the links to work, you must have Selectable checked.

    enter image description here

    0 讨论(0)
提交回复
热议问题