R
R
Roman Ekimov2016-08-23 18:36:41
iOS
Roman Ekimov, 2016-08-23 18:36:41

How to add custom css inside webview?

The bottom line is this: there is a WebView into which a string containing HTML is passed.
Looks like that:

let newsHTML = receviedNewsText
viewNewsHTML.loadHTMLString(newsHTML, baseURL: nil)

viewNewsHTML- actually, himself WebView;
receviedNewsTextis HTML (from the tags there are only p and sometimes a), which is obtained from the server via JSON.
Since there are no styles there, the text is ordinary, small, ugly.
The goal is to be able to style the p tag inside the WebView.
How can I do that? Ideally, if it will be a .css file inside the application, the styles from which will be loaded into the WebView. But maybe there is some other way.
I would be grateful for advice. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Ekimov, 2016-08-24
@toywar

The solution was found (albeit in ObjC, but it was not difficult to rewrite it in Swift):

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *cssString = @"body { font-family: Helvetica; font-size: 50px }"; // 1
    NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2
    NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3
    [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString]; // 4
}

M
Maxim Globak, 2016-08-24
@maximglobak

You can create your own .css file and, when loading html, convert it to a string and add it to the beginning of the line

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question