Swift 在不使用MainstryBoard的情况下将WebView添加到CollectionView

Swift 在不使用MainstryBoard的情况下将WebView添加到CollectionView,swift,webview,collectionview,Swift,Webview,Collectionview,我一直在研究CollectionView和每个单元格中的ImageView。现在我想知道如何添加WebView,其工作方式与ImageView相同。我想让它在每个单元格中作为一个元素工作,可能吗?此外,我没有使用故事板 import UIKit class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout { override func viewDidLoad() { supe

我一直在研究CollectionView和每个单元格中的ImageView。现在我想知道如何添加WebView,其工作方式与ImageView相同。我想让它在每个单元格中作为一个元素工作,可能吗?此外,我没有使用故事板

import UIKit

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Home"

    collectionView?.backgroundColor = UIColor.white

    collectionView?.register(WebCell.self, forCellWithReuseIdentifier: "cellId")

}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height - 500)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}
}

class WebCell: UICollectionViewCell {
override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let StronaSzkolna: UIImageView = {
   let webview = UIImageView()
    webview.backgroundColor = UIColor.blue
    webview.translatesAutoresizingMaskIntoConstraints = false
    return webview
}()

func setupViews() {
    addSubview(StronaSzkolna)

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":StronaSzkolna]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-16-[v0]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":StronaSzkolna]))

    StronaSzkolna.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

到底是什么不起作用?您是否尝试过将
UIImageView
替换为
UIWebView
WKWebView
?是的,它正在工作。但是带有URL和URLRequest以及地址的addnig代码不能正常工作。你知道怎么做吗?你介意添加执行
URLRequest
的代码吗?