iOS UIWebView totally fails to understand more tha

2019-07-24 21:52发布

问题:

Notice this simple css/html which is being displayed in a local UIWebView:

there's the simulator showing it...

Notice there are two @font-face definitions.

But ... only the second one works. If you swap them around, only the second one works.

So here ...

@font-face {
font-family:'aaa';
src: local('SourceSansPro-Regular'),
url('SourceSansPro-Regular.ttf') format('truetype');
}
@font-face {
font-family:'bbb';
src: local('SourceSansPro-BoldIt'),
url('SourceSansPro-BoldItalic.ttf') format('truetype');
}

only "bbb" works, the other one seems to be "cancelled". Then here ..

@font-face {
font-family:'bbb';
src: local('SourceSansPro-BoldIt'),
url('SourceSansPro-BoldItalic.ttf') format('truetype');
}
@font-face {
font-family:'aaa';
src: local('SourceSansPro-Regular'),
url('SourceSansPro-Regular.ttf') format('truetype');
}

only "aaa" works, the other one seems to be "cancelled".

Here's how to do it in Swift,

// load a simple UIWebView (say, an "about" or "legal" screen)
// base is in template.html
import UIKit
import WebKit
class MinorWebView:UIViewController
    {
    @IBOutlet var wv:UIWebView!
    @IBInspectable var filename:String = "?"
    // for example, "about" for "about.html"

    ...
    func makeHtml()
        {
        print("making html for ... " ,filename)

        let ourSize = grid.yourSizeDecisionMechanism
        let sizeString = String(format:"%.0f", ourSize)

        let p1 = NSBundle.mainBundle().pathForResource("template", ofType: "html")
        var html:String = try! NSString(contentsOfFile:p1!, encoding:NSUTF8StringEncoding) as String

        let p2 = NSBundle.mainBundle().pathForResource(filename, ofType: "html")
        let content:String = try! NSString(contentsOfFile:p2!, encoding:NSUTF8StringEncoding) as String

        html = html.stringByReplacingOccurrencesOfString("STUFF", withString:content)
        html = html.stringByReplacingOccurrencesOfString("SIZEPOINTS", withString:sizeString)

        print("Made html like this ---\n" ,html ,"\n------")

        wv.loadHTMLString(html as String, baseURL:nil)
        }
    }

Simply drag "template.html" and "about.html" in to the project (just as you would with an image); ensure they have target membership.

回答1:

You have an error in the <style> block: it starts with a <meta> element. This will throw the parser off; apparently it thinks that everything up until the first } is bad and needs to be discarded.

Solution: take the <meta> out of the <style>.