我如何在Swift中使用Xcode设置一个简单的应用程序,底部有标签,在视图中加载不同的网站并在浏览器中构建?但是,这些标签现在不太强制,至少视图应该在打开时显示网站。 这是我的ViewController swift的代码:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string:"http://www.google.com/")
let req = NSURLRequest(URL:url!)
self.webView!.loadRequest(req)
}
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.view = self.webView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
但是,当我打开模拟器时,视图为空白。在xcode中创建了一个单一的视图项目。
编辑:仍有问题......
答案 0 :(得分:4)
我认为您应该将WebView直接实现到代码中。这是一个例子:
import UIKit
import WebKit
class ViewController: UIViewController {
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
let website = "https://www.apple.com"
layoutWebBrowsingElements()
loadURLRequest(website)
}
func loadURLRequest(address: String) {
let siteURL = NSURL(string: address)
let request = NSURLRequest(URL: siteURL!)
webView?.loadRequest(request)
}
func layoutWebBrowsingElements() {
// It is actually better to implement a WKWebView directly in code.
let wkWebView = WKWebView(frame: view.bounds)
webView = wkWebView
wkWebView.translatesAutoresizingMaskIntoConstraints = false
//Auto-Layout Stuff
self.view.addSubview(wkWebView)
let webTopSpaceToContainer = NSLayoutConstraint(item: self.view, attribute: .TopMargin, relatedBy: .Equal, toItem: webView, attribute: .Top, multiplier: 1, constant: -20)
let webBottomSpaceToContainer = NSLayoutConstraint(item: self.view, attribute: .BottomMargin, relatedBy: .Equal, toItem: webView, attribute: .Bottom, multiplier: 1, constant: -20)
let webLeadingSpaceToContainer = NSLayoutConstraint(item: self.view, attribute: .LeadingMargin, relatedBy: .Equal, toItem: webView, attribute: .Leading, multiplier: 1, constant: 20)
let webTrailingSpaceToContainer = NSLayoutConstraint(item: self.view, attribute: .TrailingMargin, relatedBy: .Equal, toItem: webView, attribute: .Trailing, multiplier: 1, constant: -20)
let webViewConstaints = [webTopSpaceToContainer,webBottomSpaceToContainer,webLeadingSpaceToContainer,webTrailingSpaceToContainer]
self.view.addConstraints(webViewConstaints)
}
}
此配置支持自动布局和“点按状态栏以滚动到顶部”
您还应该考虑阅读WebKit's documentation,在那里您可以获得可以优化用户体验的所有属性和方法。
答案 1 :(得分:0)
尝试在故事板中设置工具栏,并使用这些操作在应用中触发网址。
答案 2 :(得分:0)
以下是您通常会如何设置的内容:
class ViewController: UIViewController {
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = view.bounds
view.addSubview(webView)
let url = NSURL(string:"https://www.google.com/")
let req = NSURLRequest(URL:url!)
webView.loadRequest(req)
}
}