【问题标题】:having trouble with UIImageView initWithImage and accessing the element at indexUIImageView initWithImage 遇到问题并访问索引处的元素
【发布时间】:2015-01-25 19:06:22
【问题描述】:

我收到此警告。不知道我需要做什么修复。 Objective-C 的新手。似乎不喜欢这条线,到达这条线后应用程序崩溃:

 UIImageView *tmp = [[UIImageView alloc] initWithImage:[data objectAtIndex:index]];

我收到的警告:

/test/ViewController.m:186:89:指向整数转换的不兼容指针将“NSNumber *__strong”发送到“NSUInteger”类型的参数(又名“无符号长”)

ViewController.m 文件:

@interface ViewController () <UICollectionViewDataSource_Draggable, UICollectionViewDelegate>
{

    NSMutableArray *data;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = (UICollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];

    NSNumber *index = [data objectAtIndex:indexPath.item];

    for (UIView *subview in cell.subviews) {
        if ([subview isKindOfClass:[UIImageView class]]) {
            [subview removeFromSuperview];
        }
    }

    UIImageView *tmp = [[UIImageView alloc] initWithImage:[data objectAtIndex:index]];
    [cell addSubview:tmp];


    return cell;
}

【问题讨论】:

  • 为什么您的data 数组似乎同时包含NSNumber 对象和UIImage 对象?

标签: objective-c uiimageview


【解决方案1】:

objectAtIndex: 方法需要 NSUInteger 参数。传递index.integerValue 值。

【讨论】:

    【解决方案2】:

    您的代码很奇怪,因为您为索引和图像访问同一个数组!为什么data 数组不只是保存图像?然后你就可以打电话给UIImage * image = [data objectAtIndex: indexPath.row];

    无论如何...

    对于你当前的问题,你只需要改变:

    NSNumber *index = [data objectAtIndex:indexPath.item];
    UIImageView *tmp = [[UIImageView alloc] initWithImage:[data objectAtIndex:index]];
    

    与:

    NSNumber *indexNumber = [data objectAtIndex:indexPath.row];
    UIImageView *tmp = [[UIImageView alloc] initWithImage:[data objectAtIndex:indexNumber.intValue];
    

    我想指出,您应该创建一个 CustomCollectionViewCell 并带有一个名为 imageView 的属性,这样您就可以更改图像,而不是每次都删除和添加 imageViews。加上只保存图像的 data 数组。 它看起来像:

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        // Dequeue or initialize a new custom cell
        CustomCollectionViewCell *cell = (UICollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    
        // Configure the cell
        cell.backgroundColor = [UIColor whiteColor];
        cell.imageView.image = [data objectAtIndex:indexPath.row];
    
        return cell;
    }
    

    您还应该将data 作为属性:

    @property NSMutableArray *data;
    

    并将其与self.data 一起使用,因此很明显它是一个属性。

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2017-04-11
      相关资源
      最近更新 更多