【问题标题】:My for loop doesn´t work well我的 for 循环不能正常工作
【发布时间】:2014-01-22 14:57:51
【问题描述】:

这是循环:

我希望将 3 张图像(称为 1.jpg, 2.jpg, 3.jpg)添加到表格的 3 行中。但是>= 不会出现视图,== 只有第一行有图像。

for (int i = 0; i >= indexPath.row; i++) {
        i++;
        NSString *number = [NSString stringWithFormat:@"%d", i];
        NSString *format = @".jpg";
        NSString *end= [NSString stringWithFormat:@"%@%@", number, format];
        cell.imageView.image = [UIImage imageNamed:end];
    }

我必须做什么?

【问题讨论】:

    标签: objective-c for-loop cell nsindexpath


    【解决方案1】:

    假设你有这样的图像:

    0.jpg
    1.jpg
    2.jpg
    ...
    

    那么你应该在 cellForRowAtIndexPath: 委托方法中这样做:

    NSString *imageName= [NSString stringWithFormat:@"%d.jpg", indexpath.row];
    cell.imageView.image = [UIImage imageNamed:imageName];
    

    没有 for 循环,没有附加。

    【讨论】:

      【解决方案2】:

      好吧,您的代码有很多问题,首先让我们从循环中的第一行开始。

      i++ 将增加i,这意味着您的步数是 2 而不是 1。

      其次,当i 大于或等于indexPath.row 时继续循环,因此如果indexPath.row 为0,则此循环将永远不会结束。

      第三你不需要那么多字符串,你可以一次格式化它

      for (int i = 0; i < indexPath.row; i++) {
          NSString *imageName= [NSString stringWithFormat:@"%d.jpg", i+1];
          cell.imageView.image = [UIImage imageNamed:imageName];
      }
      

      但现在您只是覆盖同一张图片以仅获取最新的图片显示。 如果您希望第 1 行具有 1.jpg 和第 2 行 2.jpg,则根本不需要循环。您可以直接分配图像:

      NSString *imageName= [NSString stringWithFormat:@"%d.jpg", indexPath.row+1];
      cell.imageView.image = [UIImage imageNamed:imageName];
      

      【讨论】:

      • 同样比较总是错误的:i >= indexPath.row
      • @TamásZahola:不,第一次是这样。
      • @TamásZahola,还在写所有的错误;)
      • 现在使用固定代码,您将所有 3 张图像添加到同一个单元格中:)
      • @KaszásDávid 你是对的:s 代码没有任何意义。
      猜你喜欢
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多