我正在嘗試顯示 5 個 web 視圖,并且我希望在 for 回圈中創建 web 視圖。我目前使用的代碼只創建一個 web 視圖,它應該為頁面中的每個 url 創建一個。任何幫助,將不勝感激!
import UIKit
import Foundation
import WebKit
import AVFoundation
class displayviews: UIViewController, WKUIDelegate {
var pages = ["https://example.com", "https://example", "https://example", "https://example.com", "https://example.com"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in pages{
var inti = Int(i) ?? 0
//var currentwebview = String("webView") i
let myWebView:WKWebView = WKWebView(frame: CGRect(x:0, y:CGFloat(inti*200), width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height/CGFloat(pages.count)))
myWebView.uiDelegate = self
self.view.addSubview(myWebView)
//1. Load web site into my web view
let myURL = URL(string: pages[inti])
let myURLRequest:URLRequest = URLRequest(url: myURL!)
myWebView.load(myURLRequest)
}
}
}
uj5u.com熱心網友回復:
您的代碼正在創建 5 個 webviews,問題是它們被放置在彼此的頂部,因此您只能看到最上面的一個。您可以使用如下示例中的 stackview 或對 webview 設定約束。
class ViewController: UIViewController, WKUIDelegate {
var pages = ["https://example.com", "https://example.com", "https://example.com", "https://example.com", "https://example.com"]
lazy var stackView: UIStackView = {
let view = UIStackView()
view.axis = .vertical
view.translatesAutoresizingMaskIntoConstraints = false
view.distribution = .fillEqually
self.view.addSubview(view)
NSLayoutConstraint.activate([
view.leftAnchor.constraint(equalTo: self.view.leftAnchor),
view.topAnchor.constraint(equalTo: self.view.topAnchor),
view.rightAnchor.constraint(equalTo: self.view.rightAnchor),
view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in pages{
var inti = Int(i) ?? 0
//var currentwebview = String("webView") i
let myWebView:WKWebView = WKWebView(frame: CGRect(x:0, y:CGFloat(inti*200), width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height/CGFloat(pages.count)))
myWebView.uiDelegate = self
//self.view.addSubview(myWebView)
stackView.addArrangedSubview(myWebView)
//1. Load web site into my web view
let myURL = URL(string: pages[inti])
let myURLRequest:URLRequest = URLRequest(url: myURL!)
myWebView.load(myURLRequest)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/394448.html
標籤:迅速 网络 看法 网页浏览 wkwebview配置
