【问题标题】:how to show multiple webviews/URL's under one UiViewController when the user clicks different cells当用户单击不同的单元格时,如何在一个 ViewController 下显示多个 webview/URL
【发布时间】:2016-07-13 22:23:05
【问题描述】:

我有一个应用程序,它在一个 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

【问题讨论】:

    标签: ios iphone swift uiwebview


    【解决方案1】:

    您需要保留一组网址,类似于您拥有imagearraycategoryarray 的方式。我怀疑,您将在创建类别和图像的同一位置创建这些 URL。

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

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

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

    如果你这样做,那么在你的视图控制器中你可以只保留一个数组: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 的网页时出错,您可能还需要考虑让您的视图控制器成为 UIWebView 的代理。

    【讨论】:

    • 非常感谢您。我会继续尝试并更新我的帖子。我是初学者,请原谅我的错误。谢谢帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多