ios - 如何将变量放在 UICollectionView 上并通过函数获取

标签 ios xcode swift variables cell

我需要帮助将变量放在 UICollectionView 单元格上,并稍后通过 ViewController.swift 中的函数获取 我尝试了这段代码,但在 cell.idyoutube.text 中获取变量时遇到问题

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

    if (collectionView == self.collectionView1)
    {
        var cell : FeaturedCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as! FeaturedCollectionViewCell

        var imageFilename: UIImage!


        let imgURL: NSURL = NSURL(string: "http://www.mywebsite/images/imagestvos/feature-\(indexPath.row).jpg")!
        let request: NSURLRequest = NSURLRequest(URL: imgURL)


                    imageFilename = UIImage(data: data!)!
                    cell.featuredImage.image = UIImage(data: data!)!
                    cell.idyoutube.text = "Rqr3w8scm2E"
     }


        task.resume()

        return cell
    }

    return UICollectionViewCell()

}

这里,这是通过点击激活的功能,但在获取 idyoutube.tex 变量时遇到问题。

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell : FeaturedCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as! FeaturedCollectionViewCell
    let mylink = cell.idyoutube.text
}

我不知道是否到达idyoutube我去:let cell :FeaturedCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierFeatured, forIndexPath: indexPath) as!精选CollectionViewCell

最佳答案

您不应该在 -didSelectItemAtIndexPath 调用中使用 -dequeueReusableCellWithReuseIdentifier 方法,因为此调用实际上是尝试从单元池中获取空闲单元,而不是代表该单元您正在点击。

您需要使用索引路径调用 -[UICollectionView cellForItemAtIndexPath:] ,并将其传递给 -didSelectItemAtIndexPath: 方法。 在返回的单元格中,您将找到存储的 idyoutube.text 属性。

关于ios - 如何将变量放在 UICollectionView 上并通过函数获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127932/

相关文章:

swift : "float is not convertible to int"

ios - Xcode 中的 Firebase 身份验证和实时数据库 : How do I only show data relevant to ONE user not all?

ios - 是否可以对 Storyboard发表评论?

iOS Fido2 BLE 认证器注册响应问题

ios - 滚动到顶部加载更多

ios - 从外部项目目录读取 plist 文件

swift - Xcode12.4 无法为 pod 目标合并 user_target_xcconfig

ios - 让平台连续从左向右移动然后反之亦然的最佳方法是什么?

ios - 如何为 UIbutton 提供约束

objective-c - 无法获取 Collection View 的选定项目