1

I have index.html and style.css files. In these files I have only text. And I want to show this text in my textView. If I use this code I show text from file:

class ReadViewController: UIViewController {
    
    @IBOutlet weak var textView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            guard let filePath = Bundle.main.path(forResource: "index", ofType: "html")
                else {
                    print ("File reading error")
                    return
            }

            let contents =  try String(contentsOfFile: filePath, encoding: .utf8)
            
            textView.attributedText = contents.htmlToAttributedString
        }
        catch {
            print ("File HTML error")
        }
    }
    
}

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

But in this case my text displayed without bold and other style settings. How to fix it? How to add style.css file?

User
  • 121
  • 1
  • 2
  • 11
  • 1
    Did you try to inline your style to the html file? If your html file is big, `WKWebView` might be a better solution. – wzso Sep 03 '20 at 09:09
  • @BenjaminWen No. My file size very small 10 KB – User Sep 03 '20 at 09:13
  • If your `UITextView` doesn't seem to slow things down, then it's ok. I remember I tried the `UITextView` and `NSAttributtedString` solution, but it didn't work smoothly as with `WKWebView`. – wzso Sep 03 '20 at 09:19
  • @BenjaminWen I want to create page like `AppleBooks` but load only text from html. That user can change size and etc. Therefore I am using `textView`. Is WKWebView better for this task? – User Sep 03 '20 at 09:24
  • If the content is not editable, then yes, `WKWebView` seems a better way. If it's editable, then it's much harder. You can take a look at this answer: https://stackoverflow.com/a/3643425/5492956 – wzso Sep 03 '20 at 09:29
  • @BenjaminWen My content is not editable but selectable. – User Sep 03 '20 at 09:35
  • WebView is selectable, just like you can do in a Safari page. – wzso Sep 03 '20 at 09:37

2 Answers2

1

Try adding inline css in your code. Below code should help you get started:

let myFont = UIFont.systemFont(ofSize: 15)
let myHtmlText = "Html content goes here.."
let modifiedFont = String("<span style=\"font-family: \(myFont.fontName); font-size: \(myFont.pointSize); color:rgb(255,255,255);\">\(myHtmlText)</span>")


guard let data = modifiedFont.data(using: .utf8) else {
    return
}

do {
    textView.attributedText = try NSAttributedString(data: data,
                                                     options: [.documentType: NSAttributedString.DocumentType.html,
                                                               .characterEncoding:String.Encoding.utf8.rawValue],
                                                     documentAttributes: nil)
} catch {

     // handle error
}

Try to convert your html file in multiline string if the file size is smaller, as mentioned in above answer

Dhaval H. Nena
  • 3,992
  • 1
  • 37
  • 50
  • In this case all text have one style. But how I can change only titles in text to bold for example? – User Sep 03 '20 at 09:34
  • Can you share your text to bold? – Dhaval H. Nena Sep 03 '20 at 09:35
  • I only need to bold the titles. I am not good at html(modifiedFont formula). Could you show me how to solve my problem? And give a link ... So that I can show several types of text in the `textView` – User Sep 03 '20 at 09:41
  • I want to get result like this: https://ibb.co/nD2gDhF bold and regular text in different sizes – User Sep 03 '20 at 09:47
  • see https://www.tutorialspoint.com/how-to-use-bold-and-non-bold-text-in-a-single-uilabel-in-ios-iphone – Dhaval H. Nena Sep 03 '20 at 09:47
  • What if I have multiple bold titles in different places within regular text? I need to create new strings for all titles. this is not very convenient – User Sep 03 '20 at 09:54
  • then find the range of each text to bold and add the attributes accordingly! – Dhaval H. Nena Sep 03 '20 at 12:15
0

You can also use extension like below:

extension NSAttributedString {

    static func bolded(originalText:String, wordsToBold:[String], color:UIColor, font:UIFont, fontBold:UIFont? = nil) -> NSAttributedString {
        
        let fontBoldTemp = fontBold ?? UIFont.appFont_Bold(fontSize: font.pointSize)
        
        let attr = NSMutableAttributedString(string: originalText)
        attr.addAttributes([NSAttributedString.Key.font : font,
                            NSAttributedString.Key.foregroundColor : color], range: NSRange(location: 0, length: originalText.count))
        for eachWord in wordsToBold {
            attr.addAttributes([NSAttributedString.Key.font : fontBoldTemp,
                                NSAttributedString.Key.foregroundColor : color], range: (originalText as NSString).range(of: eachWord))
        }
        
        return attr
    }
}

then use it as below:

textView.attributedText = NSAttributedString.bolded(originalText: "This is sample text Bold1 and another Bold2",
                                 wordsToBold: ["Bold1", "Bold2"],
                                 color: UIColor.red,
                                 font: UIFont.systemFont(ofSize: 13))
Dhaval H. Nena
  • 3,992
  • 1
  • 37
  • 50