【问题标题】:Strange UICollectionView Selection Behavior奇怪的 UICollectionView 选择行为
【发布时间】:2013-01-29 18:15:59
【问题描述】:

我正在使用UICollectionView 来显示一个菜单,并且正在以一种非常奇怪的方式选择项目。

这是填充它们的静态数据:

self.menuItems = @[@{@"text" : @"First", @"image" : @"180-stickynote.png"},
                   @{@"text" : @"Second", @"image" : @"180-stickynote.png"},
                   @{@"text" : @"Third", @"image" : @"180-stickynote.png"},
                   @{@"text" : @"Fourth", @"image" : @"180-stickynote.png"},
                   @{@"text" : @"Fifth", @"image" : @"180-stickynote.png"},
                   @{@"text" : @"Sixth", @"image" : @"180-stickynote.png"}];

还有单元格提供者,其中自定义子类只是附加到原型单元格,并且有一个UILabel 和一个UIImageView

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    CUMenuCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MenuCell" forIndexPath:indexPath];

    NSDictionary *cellInfo = [self.menuItems objectAtIndex:indexPath.row];

    cell.imageView.image = [UIImage imageNamed:[cellInfo valueForKey:@"image"]];

    cell.label.text = [cellInfo valueForKey:@"text"];

    return cell;
}

这里是 did select row 方法,记录标题和项目的行(它们都在第 0 部分):

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@: %d", [[self.menuItems objectAtIndex:indexPath.row] valueForKey:@"text"], indexPath.row);
}

最后,我的菜单截图:

这是当我从第一到第六选择项目,然后从第六到第一(第一,第二,第三,第四,第五,第六,第六,第五,第四,第三,第二,第一)选择项目时的日志(12总点击次数,注意第一次点击甚至没有记录,第二次点击第六次也没有):

------------------------------------- FIRST TAP ON FIRST HERE
2013-02-13 19:38:37.343 App[1383:c07] First: 0  // second tap, on Second
2013-02-13 19:38:38.095 App[1383:c07] Second: 1 // third tap, on Third
2013-02-13 19:38:38.678 App[1383:c07] Third: 2  // fourth tap, on Fourth
2013-02-13 19:38:39.375 App[1383:c07] Fourth: 3 // fifth tap, on Fifth
2013-02-13 19:38:40.167 App[1383:c07] Fifth: 4  // so on
2013-02-13 19:38:41.751 App[1383:c07] Sixth: 5
------------------------------------- SECOND TAP ON SIXTH HERE
2013-02-13 19:38:42.654 App[1383:c07] Fifth: 4
2013-02-13 19:38:43.318 App[1383:c07] Fourth: 3
2013-02-13 19:38:44.495 App[1383:c07] Third: 2
2013-02-13 19:38:45.071 App[1383:c07] Second: 1

【问题讨论】:

    标签: ios objective-c xcode uistoryboard uicollectionview


    【解决方案1】:

    那是因为您使用的是didDeselectItemAtIndexPath: 方法而不是didSelectItemAtIndexPath:。很容易犯错误,尤其是当您在输入代码时使用代码完成时。

    【讨论】:

    • 哇。我可能会尖叫一点,现在为时已晚。非常感谢,真诚的!
    • @Josh,没问题,这是我犯过不止一次的错误。
    • 哇。也犯了这个错误。以为有一些黑暗魔法在起作用。但不是。让我自己被愚弄了很多次:)
    • 自从 6 小时以来,我一直在寻找为什么我选择以前的一个 :-)
    • StackOverflow... 我觉得时间旅行已成为现实!你不知何故从过去来到了未来,阅读了我刚刚写的一些代码并指出了一个错字。这个网站很棒,你也一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2011-08-19
    • 2013-04-27
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多