[背景]
Swift中需要,创建一个新的页面,去显示一个已有链接地址的网页内容。
[折腾过程]
1.搜:
swift show web page from url
参考:
去试试:
let webView = UIWebView() let requestURL = NSURL(fileURLWithPath: REGISTRATION_AGREEMENT_URL) let request = NSURLRequest(URL: requestURL) webView.loadRequest(request) self.view.addSubview(webView)
结果是可以编译通过了,但是又出现:
然后虽然还没解决上面问题,但是此处的代码,却验证了没有起效果,没有显示网页
3.换成:
let webView = UIWebView() self.view.addSubview(webView)let requestURL = NSURL(fileURLWithPath: REGISTRATION_AGREEMENT_URL) letrequest =NSURLRequest(URL: requestURL) webView.loadRequest(request) |
import UIKit import WebKit class RegistrationAgreementController : UIViewController { var webView: WKWebView? // init() { // super.init(nibName: nil, bundle: nil) // } // // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // } override func viewDidLoad() { super.viewDidLoad() ... let webView = UIWebView() self.view.addSubview(webView) let requestURL = NSURL(fileURLWithPath: REGISTRATION_AGREEMENT_URL) let request = NSURLRequest(URL: requestURL) //webView.loadRequest(request) self.webView!.loadRequest(request) } override func loadView() { super.loadView() self.webView = WKWebView() self.view = self.webView! }
结果:
屏幕是白屏:
调试好多次,最终把改代码为:
import UIKit import WebKit class RegistrationAgreementController : UIViewController { var webView: WKWebView? override func viewDidLoad() { super.viewDidLoad() let requestURL = NSURL(string: "http://www.baidu.com") let request = NSURLRequest(URL: requestURL!) self.webView!.loadRequest(request) } override func loadView() { super.loadView() self.webView = WKWebView() self.view = self.webView! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
效果是:
5.然后再去想办法:
6.然后再去把顶部的导航加上,变成:
import UIKit import WebKit class RegistrationAgreementController : UIViewController { override func viewDidLoad() { super.viewDidLoad() 。。。 let curHeight = statusView.frame.height + tabbgView.frame.height let webView = WKWebView() webView.frame = CGRectMake(0, curHeight, self.view.frame.size.width, self.view.frame.size.height - curHeight) let requestURL = NSURL(string: REGISTRATION_AGREEMENT_URL) let request = NSURLRequest(URL: requestURL!) webView.loadRequest(request) self.view.addSubview(webView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
效果:
很明显,文字太小,所以再去优化:
7.但是结果字体没有解决。
所以,算了,暂时去换用UIWebView看看:
[总结]
最终用UIWebView可以正常显示网页内容了。
代码详见:
转载请注明:在路上 » [已解决]Swift中创建页面显示网址链接的网页内容