我在加载本地 HTML 文件时遇到问题。这是我的代码。请帮忙。
let URL = NSBundle.mainBundle().pathForResource("index2", ofType: "html")
let request = NSURLRequest(URL: url!)
Webview.loadRequest(request)
使用以下代码。我已设法加载 html 文件,但它没有加载 CSS!
让 htmlFile = NSBundle.mainBundle().pathForResource("index1", ofType: "html") 让 html = 试试?字符串(contentsOfFile:htmlFile!,编码:NSUTF8StringEncoding) GSFWebView.loadHTMLString(html!, baseURL: nil)
最佳答案
只需将这段代码写在你的 ViewDidLoad 中,我已经添加了这个页面的 url 作为示例,只需将其替换为你的。在 Storyboard 上,您无需执行任何操作,如果您在 View Controller 上添加了任何额外的 View 作为网站的容器,则将我的代码中的 self.view
替换为您的 View 。
let myWebView:UIWebView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
//add your url on line below
myWebView.loadRequest(URLRequest(url: URL(string: "https://stackoverflow.com/questions/26647447/load-local-html-into-uiwebview-using-swift")!))
self.view.addSubview(myWebView)
如果你想从本地文件加载页面,你可以通过这种方式定义 url 来实现。
swift 2
let url = NSBundle.mainBundle().URLForResource("webFileName", withExtension:"html")
swift 3
let url = Bundle.main.url(forResource: "webFileName", withExtension: "html")
关于swift - 在 UIWebView 中加载本地 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749253/