在for循环swift中创建多个Web视图



我正在尝试显示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)
}
}
}

您的代码正在创建5个Web视图,问题是它们被放置在彼此的顶部,因此您只能看到最顶部的一个。您可以像下面的例子一样使用stackview,也可以在web视图上设置约束。

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 (inti, page) in pages.enumerated() {
//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: page)
let myURLRequest:URLRequest = URLRequest(url: myURL!)
myWebView.load(myURLRequest)
}

}
}

最新更新