簡體   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