从所选集合视图单元格中获取信息

时间:2015-10-05 00:45:11

标签: ios swift uicollectionview uicollectionviewcell

我正在尝试从集合视图单元格中打印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)
    }

但它没有显示任何文字。

2 个答案:

答案 0 :(得分:0)

如果您只是获取数据本身,而不是尝试获取单元?请勿查看collectionView(强调查看),而是从数据来源中提取数据。

您可以使用

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

并在该方法中调用

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

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

答案 1 :(得分:0)

请原谅我的语法错误,我从来没有做过快速: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)
}