1

我有一类 type UICollectionViewController。在这个类中,我有 a 标签的变量UICollectionViewCell

var cellTitle = UILabel()

我也有 collectionView 方法cellForItemAtIndexPath

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    var definitions = shuffle(["Used to carry the pharoah","Used to carry bodies as a ceremony","Had a flat deck to carry a farmer's treasure","Daily, it made a trip around the world to carry Ra","Towed by smaller boats, carrying heavy objects","Used for business and pleasure by officials/nobles","Carried most Egyptians and some goods"])
    var boatTypes = shuffle(["Ferry","Funeral Barge","Cargo Boat","Cattle Boat","Royal Boat","The Sun Boat","Grand Boat"])
    // Configure the cell
    cellTitle = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 160))
    cell.contentView.addSubview(cellTitle)
switch indexPath.item {
    case 0:
        cellTitle.text = definitions[0]
    case 1:
        cellTitle.text = definitions[1]
    case 2:
        cellTitle.text = definitions[2]
    case 3:
        cellTitle.text = definitions[3]
    case 4:
        cellTitle.text = definitions[4]
    case 5:
        cellTitle.text = definitions[5]
    case 6:
        cellTitle.text = definitions[6]
    case 7:
        cellTitle.text = boatTypes[0]
    case 8:
        cellTitle.text = boatTypes[1]
    case 9:
        cellTitle.text = boatTypes[2]
    case 10:
        cellTitle.text = boatTypes[3]
    case 11:
        cellTitle.text = boatTypes[4]
    case 12:
        cellTitle.text = boatTypes[5]
    case 13:
        cellTitle.text = boatTypes[6]
    default:
        break

我也有一个didSelectItemAtIndexPath方法:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    var selectedText = cellTitle.text
    switch indexPath.item {
    case 0:
        if selectedText == "Used to carry the pharoah" {
            println("Used to carry the pharoah")
        } else {
            println("Not Working")
        }

问题是,当我按下标签确实包含“用于携带法老”文本的单元格时,println("Not Working")会触发。如何将值从cellForItemAtIndexPath方法传递给didSelectItemAtIndexPath方法,使值cellTitle保持不变?谢谢你。

4

1 回答 1

0

当要显示每个项目时,都会为每个项目调用 cellForItemAtIndexPath。您正在对字符串数组应用某种“洗牌”?因此,并非所有字符串都必须使用,并且一些字符串将具有相同的文本。您可以简单地全局初始化变量“定义”和“船”,然后像这样访问值:

if indexPath.item < 7 {
    selectedText = definitions[indexPath.item]
} else {
    selectedText = boatTypes[indexPath.item]
} 
于 2014-12-17T22:14:22.783 回答