gpt4 book ai didi

ios - 当用户单击不同的单元格时,如何在一个 UiViewController 下显示多个 webview/URL

转载 作者:行者123 更新时间:2023-11-30 13:14:42 24 4
gpt4 key购买 nike

我有一个应用程序,其中一个 UICollectionView 中有 12 个单元格。我希望当用户单击每个单元格时,它应该在一个 WebView 中打开相应的网站,就像第一个应该打开 facebook 另一个应该打开 twitter 等..

UICollectionView 中创建单元格的代码如下,我需要知道如何创建一个可能包含 url 的数组并将其传递给所有单元格以显示网站。

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.category.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionview.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell1

cell.imageopenview.image = self.imagearray[indexPath.row]

cell.titlelabel .text = self.category[indexPath.row]


return cell

最佳答案

您需要保留一个 URL 数组,类似于 imagearraycategoryarray。我怀疑,您将在创建类别和图像的同一位置创建这些 URL。

我还建议您遵循变量的 Swift 驼峰命名约定(例如“imageArray”和“categoryArray”)。

由于 Collection View 中的每个单元格都是具有图像、类别标题和 URL 的不同单元,因此存储单个结构数组而不是三个单独的数组也是有意义的。

struct SocialMediaSite {
var image: UIImage
var title: String
var URL: NSURL
}

如果您这样做,那么在 View Controller 中您可以只保留一个数组:data: [SocialMediaSite]。确保在设置图像和类别数组的相同位置使用适当的数据设置此数组。您还需要在此处设置您希望每个单元格对应的网站的 URL。您使用 NSURL(string: "http://www.somesite.com") 创建 NSURL 并将其存储在 URL 变量中。

使用单个数据数组,您的函数(也遵循 Swift 命名约定)将如下所示:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell1

cell.imageOpenView.image = data[indexPath.row].image
cell.titleLabel .text = data[indexPath.row].title

return cell
}

这将在 UICollectionView 中显示您当前拥有的内容的单元格。现在,要在点击单元格时在 UIWebView 中加载对网站的请求,您必须实现另一个 UICollectionViewDelegate 方法: func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)。每当用户点击单元格时都会调用此函数。

在此函数中,您可以执行以下操作:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let selectedCellData = data[indexPath.row]

let url = selectedCellData.URL // This is the website you want to go to for the cell you just tapped
webView.loadRequest(NSURLRequest(URL: url)) // Tell the webView to load this URL

...
}

如果您想在加载网页时执行任何操作,或者加载该 URL 的网页时出错,您可能还需要考虑让 View Controller 成为 UIWebView 的委托(delegate)。

关于ios - 当用户单击不同的单元格时,如何在一个 UiViewController 下显示多个 webview/URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com