在ios中的tableview中设置所选单元格上的imageview的问题

时间:2014-03-06 04:40:54

标签: ios objective-c uitableview uiimageview

我有一个应用程序,我在我的tableview中显示一些数据,如下面的ScreenShot1所示。

Screenshot1。

enter image description here

现在我在每个tableview单元格上都有一个imageview。

如果我从tableview中选择任何一个单元格,我想在所选单元格上有一个图像,如下面的截图2所示。

Screenshot2。

enter image description here

现在如果我选择任何其他单元格表格视图。我想仅在那些选定的单元格上设置我的imageview图像,如下面的屏幕截图3所示。

enter image description here

以下是我正在做的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }
   lblRecipe  = [[UILabel alloc] initWithFrame:CGRectMake(50, 5, 600, 32)];

    lblRecipe.backgroundColor = [UIColor clearColor];

    lblRecipe.font = [UIFont systemFontOfSize:20.0f];
    [cell.contentView addSubview:lblRecipe];
   checkedimg=[[UIImageView alloc]initWithFrame:CGRectMake(40, 20, 500, 5)];

    [cell.contentView addSubview:checkedimg];
   lblRecipe.text = [array objectAtIndex:indexPath.row];
  return cell;

}

在Tableview的didselect方法中,我应该保留什么才能拥有这种功能?

我搜索了很多,但有很多问题,但找不到一个。

所以请帮我解决这个问题。

提前致谢。

4 个答案:

答案 0 :(得分:3)

你可能最好只是继承UITableViewCell,因为这可以让你改变单元格的绘制方式,并添加一个属性或类似的东西来表示这种状态。

要创建子类,请在Xcode中创建一个新文件,并选择UITableViewCell作为其超类。

然后,在该子类中,您可以实现一个名为setStrikeThrough:的方法,您可以调用从表中出列的单元格:

- (void) setStrikeThrough:(BOOL) striked {
    if(striked) {
        // create image view here and display, if it doesn't exist
    } else {
        // hide image view
    }
}

然后,在保存表的视图控制器中,您将在viewDidLoad中调用此方法以使用表视图注册您的子类:

[_tableView registerClass:[YourAmazingTableCell class] forCellReuseIdentifier:@"AmazingCellSubclass"];

然后,您可以将tableView:cellForRowAtIndexPath:更改为:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"AmazingCellSubclass";

    YourAmazingTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[YourAmazingTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // here you would look up if this row should be selected
    [cell setStrikeThrough:YES];

    // Set up the remainder of the cell, again based on the row
    cell.textLabel.text = @"chilli";

    return cell;
}

答案 1 :(得分:3)

试试这个,

添加NSMutableArray checkedCellArray,作为属性和alloc init。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

if (cell == nil) {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    UILabel *labelRecipe  = [[UILabel alloc] initWithFrame:CGRectMake(50, 5, 600, 32)];

    labelRecipe.backgroundColor = [UIColor clearColor];

    labelRecipe.font = [UIFont systemFontOfSize:20.0f];
    labelRecipe.tag = kRecipeTag;//a tag to label
    [cell.contentView addSubview:labelRecipe];
    UIImageView *checkedimg = [[UIImageView alloc]initWithFrame:CGRectMake(40, 20, 500, 5)];
    [checkedimg setImage:[UIImage imageNamed:@"checked.png"];
    checkedimg.tag = kCheckedImageTag;//a tag to imageView
    [cell.contentView addSubview:checkedimg];
    checkedimg.hidden = YES;
}

UILabel *labelRecipe  = (UILabel *)[cell.contentView viewWithTag:kRecipeTag];
UIImageView *checkedimg = (UIImageView *)[cell.contentView viewWithTag:kCheckedImageTag];
if ([self.checkedCellArray containsObject:indexPath]) {
    checkedimg.hidden = NO;
} else {
    checkedimg.hidden = YES;
}
labelRecipe.text = [array objectAtIndex:indexPath.row];
return cell;

}

并在didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (![self.checkedCellArray containsObject:indexPath]) {
        [self.checkedCellArray addObject:indexPath];
    }
    NSArray* rowsToReload = [NSArray arrayWithObjects:indexPath, nil];
   [UITableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];
}

答案 2 :(得分:1)

Oky听说你可以这样做

只是将tableview单元格子类化

<{1>}文件中的

CustomCell.h
<{1>}文件中的

 #import <UIKit/UIKit.h>

 @interface CustomCell : UITableViewCell
 @property (nonatomic,retain)UIImageView *dashImageView; //add a property of image view

 @end

编辑:2 * 用于选择表格视图的部分和行 *

控制器中的自定义单元格更改没有变化,因此您可以反映您对tableview单元格所做的更改,即天气选择或取消选择 因为你想要选择部分以及所选行。(你的要求)有各种方法可以做到这一点,但我会使用一些包含索引部分和行的模型对象。

为此你需要创建一个NSObject的子类,然后将其命名为CustomCell.m 在MySelectedIndex.h文件中

#import "CustomCell.h"

@implementation CustomCell
{
   BOOL isCellSelected; //add this to check
}

@synthesize dashImageView = _dashImageView; //synthesize it

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
   self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
   if (self) {
    // Initialization code
     isCellSelected = NO;//initially set it no
    _dashImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.bounds.origin.x + 15, self.bounds.origin.y + 10, self.bounds.size.width, 15.0f)];
    _dashImageView.backgroundColor = [UIColor redColor];
    _dashImageView.tag = 12345;
    _dashImageView.hidden = YES;
    [self.contentView addSubview:_dashImageView];

   }
   return self;
 }

 - (void)setSelected:(BOOL)selected animated:(BOOL)animated
 {
     [super setSelected:selected animated:animated];
if(selected)
{
    UIImageView *dashImageVIew = (UIImageView *)[self viewWithTag:12345];
    if(dashImageVIew)
    {
        if(!isCellSelected)
        {
            dashImageVIew.hidden = NO;
            isCellSelected = YES;
        }
        else
        {
            dashImageVIew.hidden = YES;
            isCellSelected = NO;
        }
    }
}


}
MySelectedIndex.m文件中的

MySelectedIndex

现在回到控制器,你正在使用表

<。>文件中的

 #import <Foundation/Foundation.h>

 @interface MySelectedIndex : NSObject<NSCoding>//to store and retrieve data like user   defaults, for non-property list objects, confirms to NSCoding protocol
 @property (nonatomic,retain) NSNumber *selectedRow;
 @property (nonatomic,retain) NSNumber *selectedSection;

 - (id)initWithSelectedRow:(NSNumber *)selRow andSelectedIndex:(NSNumber *)selSection;

 @end

并在方法中

#import "MySelectedIndex.h" @implementation MySelectedIndex @synthesize selectedSection = _selectedSection; @synthesize selectedRow = _selectedRow; - (id)initWithSelectedRow:(NSNumber *)selRow andSelectedIndex:(NSNumber *)selSection { self = [super init]; if(self) { _selectedRow = selRow; _selectedSection = selSection; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_selectedRow forKey:@"ROW"]; [aCoder encodeObject:_selectedSection forKey:@"SECTION"]; } -(id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if(self) { _selectedRow = [aDecoder decodeObjectForKey:@"ROW"]; _selectedSection = [aDecoder decodeObjectForKey:@"SECTION"]; } return self; } @end

中的

    import it #import "CustomCell.h"

正如你所说,你正在使用按钮弹出这个viewcontroller所以你已经知道在哪里放置所以把它放在所有的动作方法中(只需替换你保存到用户默认值的地方) 并阅读我在代码中的评论

viewController.m

通过以下代码替换 @interface SampleViewController ()<UITableViewDataSource,UITableViewDelegate> { NSMutableArray *indexes;//to store in defaults NSMutableArray *indexesRed;//to red from the defaults } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. //...other stuff's indexes = [[NSMutableArray alloc]init];//initilise your arrays indexesRed = [[NSMutableArray alloc]init]; //after initilizing your array NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"SELECTED_CELLL"]; if(data != nil) { indexes = [NSKeyedUnarchiver unarchiveObjectWithData:data]; [indexes retain];//you hav to retain the objects other wise u will get crash, make sure u will release it by proper memory mabagement (if u are not using ARC) } } (我在下面的方法中添加)

//put all these codes where u poping this viewcontroller 
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:indexes];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"SELECTED_CELLL"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.navigationController popViewControllerAnimated:YES]; 

最后在方法cellForRowAtIndexPath中替换为以下方法

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath
  {
      CustomTabedCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
      if(Cell == nil)
      {
         Cell = [[CustomTabedCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
      }

      Cell.textLabel.text = @"Apple";
      NSNumber *rowNum = [NSNumber numberWithInt:indexPath.row];
      NSNumber *secNum = [NSNumber numberWithInt:indexPath.section];
      __block BOOL isImageHidden = YES;
     [indexes enumerateObjectsUsingBlock:^(MySelectedIndex *obj, NSUInteger idx, BOOL *stop)
       {
          if(obj.selectedRow == rowNum && obj.selectedSection == secNum)
         {
           isImageHidden = NO;
         }
      }];
    Cell.dashImageView.hidden = isImageHidden;
    [Cell.contentView bringSubviewToFront:Cell.dashImageView];//as i notised the red dash imageview appers below the text, but in your image it is appearing above the text so put this line to bring the imageview above the text if dont want commnent this

    return Cell;

 }

编辑无法选择超过13行的

didSelectRowAtIndexPath

中的

喜欢这个

  - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
      NSNumber *selSection = [NSNumber numberWithInt:indexPath.section];
      NSNumber *selRow = [NSNumber numberWithInt:indexPath.row];
     if([indexes count] == 0)
     {
        MySelectedIndex *selectedIndx = [[MySelectedIndex alloc]initWithSelectedRow:selRow andSelectedIndex:selSection];
       [indexes addObject:selectedIndx];
    }
   else if ([indexes count] == 1)
   {
     MySelectedIndex *singleIndex = [indexes objectAtIndex:0];
     if(singleIndex.selectedSection == selSection & singleIndex.selectedRow == selRow)
     {
        [indexes removeAllObjects];
     }
     else
    {
        MySelectedIndex *selectedIndx = [[MySelectedIndex alloc]initWithSelectedRow:selRow andSelectedIndex:selSection];
        [indexes addObject:selectedIndx];
    }
  }
  else
 {
     __block BOOL addSelectedRow = NO;
     __block int index = -1;
     [indexes enumerateObjectsUsingBlock:^(MySelectedIndex *obj, NSUInteger idx, BOOL *stop)   {
        if(!((obj.selectedRow == selRow) & (obj.selectedSection == selSection)))
        {
           addSelectedRow = YES;
        }
         else
         {
            index = idx;
            addSelectedRow = NO;
            *stop = YES;
        }
      }];
      if(addSelectedRow)
       {
          MySelectedIndex *selectedIndx = [[MySelectedIndex alloc]initWithSelectedRow:selRow andSelectedIndex:selSection];
          [indexes addObject:selectedIndx];
       }
       else
       {
         if(index >= 0)
         {
             [indexes removeObjectAtIndex:index];
         }
       }
    }
   NSLog(@"%@",indexes.description);
   [tableView reloadData];

  }

多数民众赞成...... :) 希望这有助于你.. :))

答案 3 :(得分:1)

尝试这样做效果很好

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *menuTableView;
    NSMutableArray *colorsArray,*tagvalueArray;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
menuTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 60, 320, 404) style:UITableViewStyleGrouped];
menuTableView.delegate=self;
menuTableView.dataSource=self;
menuTableView.separatorColor=[UIColor grayColor];
[self.view addSubview:menuTableView];
NSArray *serverResponseArray=[[NSArray alloc]initWithObjects:@"red",@"yellow",@"pink",@"none", nil]; // consider this array as the information you receive from DB or server
colorsArray =[[NSMutableArray alloc]init];
tagvalueArray =[[NSMutableArray alloc]init];

for (int i=0; i<serverResponseArray.count; i++) {

    [colorsArray addObject:serverResponseArray[i]];
    [tagvalueArray addObject:@"0"];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return colorsArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}  
for (UIView *view in cell.contentView.subviews) {
     [view removeFromSuperview];
}
cell.textLabel.text =colorsArray[indexPath.row];
if ([[tagvalueArray objectAtIndex:indexPath.row]intValue]==1) {
    UIImageView *checkedimg=[[UIImageView alloc]initWithFrame:CGRectMake(40, 20, 500, 5)];
    checkedimg.backgroundColor=[UIColor redColor];
    [cell.contentView addSubview:checkedimg];        
    }
 return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",colorsArray[indexPath.row]);
    [tagvalueArray replaceObjectAtIndex:indexPath.row withObject:@"1"];
    [menuTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end