繁体   English   中英

从选定的集合视图单元格获取信息

[英]Get info from selected collection view cell

我正在尝试从集合视图单元格打印cell.image.text

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

        let post = self.arrayOfDetails[indexPath.row]
        cell.currentUserLabel.text = post.username
        cell.imageText.text = post.text

        cell.uploadedTimeLabel.text = post.CreatedAt.timeAgo

        cell.imageView.setImageWithUrl(NSURL(string: post.image)!, placeHolderImage: UIImage(named: "Placeholder"))

        return cell
    }

ArrayOfDetails:

var arrayOfDetails = [Details]()

细节:

struct Details {
    var username:String!
    var text:String!
    var CreatedAt:NSDate!
    var image:String!
    init(username:String,text:String,CreatedAt:NSDate,image:String){

        self.username = username
        self.text = text
        self.CreatedAt = CreatedAt
        self.image = image
    }
}

这就像一个Instagram应用程序,因此有多个包含照片和照片文字的单元格,并且我有一个按钮,当按下按钮时,它要println(cell.image.text) 我怎样才能做到这一点?

我试过了:

@IBAction func printButton(sender: AnyObject) {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: nil) as! CollectionViewCell

        println(cell.imageText.text)
    }

但是它没有显示任何文字。

与其尝试获取单元 ,不如仅获取数据本身该怎么办? 不要看collectionView (强调View ),而是从数据源中提取数据。

你可以用

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath

然后在该方法中调用

println(self.arrayOfDetails[indexPath.row].text)

如果您想在用户选择单元格时打印出文本。

请原谅我的语法错误,我从没做过swift:D

首先,您创建一个CustomCollectionViewCell,它继承了CollectionViewCell。

现在在标题中,给它一个printButton属性:

var printButton: UIButton!

然后在CustomCollectionViewCell类实现中:

// This is lazy loading, everytime something needs to talk to the printButton 
// of a cell, it checks if this button exists. If not, it will be created.
lazy var printButton: UIButton = 
{
    var temporaryButton: UIButton = UIButton()
    temporaryButton.frame = self.contentView.bounds;
    temporaryButton.addTarget(self action: @selector(printText), forControlEvents: TouchUpInside);
    self.contentView.addSubview(temporaryButton);
    return temporaryButton;
}()

    return _printButton;
}

然后,当子类单元被重用时,您将删除printButton:

func prepareForReuse()
{
    super.prepareForReuse();

    self.printButton.removeFromSuperview().
    self.printButton = nil;
}

最后,实现您的printText函数

func printText()
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: nil) as! CollectionViewCell

    println(cell.imageText.text)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM