【问题标题】:UITableView - didSelectRowAtIndexPath Question? [duplicate]UITableView - didSelectRowAtIndexPath 问题? [复制]
【发布时间】:2011-11-21 13:26:07
【问题描述】:

可能重复:
UITableView and Selecting Items

我正在构建一个 iPad 应用程序,并且在 UITableView 中有十个项目。当我选择选项“Apple”时,我希望它在右侧的 UIImageView 中显示一个苹果。当我选择“橙色”时,我希望它在右侧的 UIImageView 中显示橙色,依此类推。

完成此任务的最简单的代码是什么?

【问题讨论】:

    标签: objective-c xcode ipad ios4 xcode4


    【解决方案1】:

    假设您已经将您正在显示的值存储在某种 NSArray 或其他类型的数据源(我将假设为 NSArray)中,那么您可以执行以下操作:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSString *selection = [myArray objectAtIndex:indexPath.row];
    
        if ([selection isEqualToString:@"Apple"])
        {
            [myImageView setImage:[UIImage imageNamed:@"Apple.png"]];
        }
        elseif ([selection isEqualToString:@"Orange"])
        {
            [myImageView setImage:[UIImage imageNamed:@"Orange.png"]];
        }
    }
    

    【讨论】:

      【解决方案2】:

      我已经为你回答了这个问题。

      Here is the SO question

      如果您仍然需要有关 UITableView 的帮助,最好用评论来回答同样的问题。

      这是另一个问题的答案。


      要么设置 cell.imageView.highlightedImage,要么在 didSelectRowAtIndexPath 方法中,将 cell.imageView.image 从 nil 更改为一些 [UIImage imageNamed:@"myImage.png"]:

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
          static NSString *kCustomCellID = @"com.me.foo.cell";
          UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
          cell.textLabel.highlightedTextColor = [UIColor blueColor];
          cell.imageView.image = nil;
          cell.imageView.highlightedImage = [UIImage imageNamed:@"myImage.png"];
          return cell;
      }
      
      - (void)tableView:(UITableView *)tableView willDisplayCell:(iPadRootViewControllerTableCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
          cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
      }
      
      - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
          // Do this if you didnt set the highlightedImage in cellForRowAtIndexPath
          // [self tableView:tableView cellForRowAtIndexPath:indexPath].imageView.image = [UIImage imageNamed:@"myApple.png"];
      }
      

      编辑(添加来自其他问题答案的 cmets):

      要从数组中获取特定项目的行,只需使用 indexPath.row 作为数组的 objectForIndex。

      【讨论】:

        【解决方案3】:

        在Thuggish Nugget's answer 的基础上,您可以将选择名称直接合并到图像字符串中:

        NSString *selection = [myArray objectAtIndex:indexPath.row];
        [myImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@.png", selection]]];
        

        你可以把它浓缩成一行。

        【讨论】:

        • 非常感谢。你的帮助超级大!!
        猜你喜欢
        • 2014-12-22
        • 2012-01-14
        • 1970-01-01
        • 2013-10-15
        • 2012-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多