我想像我在 didSelectRowAtIndexPath
方法中所做的那样永久更改选定的单元格数据,但问题是,当我选择一行时,单元格数据会发生变化,但当我选择任何其他行时, previous 变成原样了,我还想将行保存在一个数组中,那些在数组中被选中的行。这是我的代码。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
@try {
static NSString *cellidentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier];
if(cell == nil)
{
NSArray *cellObjects = [[NSBundle mainBundle] loadNibNamed:@"Cell" owner:self options:nil];
cell = (UITableViewCell*) [cellObjects objectAtIndex:0];
}
UILabel *label;
long row = [indexPath row];
label = (UILabel *)[cell viewWithTag:10];
label.text =time[row];
label.textColor = [UIColor blackColor];
cell.imageView.image = [img_clock_blue objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor yellowColor];
[tableView setSeparatorInset:UIEdgeInsetsZero];
//int hecValue;
return cell;
}
@catch (NSException *exception)
{
NSLog(@"%@",exception);
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView reloadData];
UITableViewCell *cell1 = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell1.imageView.image = [UIImage imageNamed:@"1_red.png"];
cell1.backgroundColor = [UIColor clearColor];
}
最佳答案
您正在修改单元格,这是个坏主意。您需要修改它获取数据的位置。
在您的didSelectRowAtIndexPath
中找到数组中的objectAtIndex:
,根据您的意愿修改它,然后重新加载表格。
例如,如果您只有标题 (NSStrings
),那么一个字符串数组就足够了。但大多数情况下它不会,因为您要显示自定义内容。
看来你这里没有自定义类,所以我就举个例子,你可以很容易地翻译。假设您正在尝试显示 Animal
对象的列表。
创建继承自 NSObject 的 Animal
类。 (新文件、类等)。
例如,在 Animal.h
文件中添加您需要的属性
@property (weak, nonatomic) NSString *name;
@property (nonatomic) int size;
@property (nonatomic) int weight;
@property (weak, nonatomic) NSString *countryOfOrigin;
从技术上讲,您还需要一个类来创建/管理/获取/保存这些 Animal
对象,但让我们保持简单,在 Controller 的 viewDidLoad
中完成.
- (void)viewDidLoad{
[super viewDidLoad];
Animal *myAnimal = [[Animal alloc]init];
myAnimal.name = @"Lion";
myAnimal.size = 13;
myAnimal.weight = 100;
myAnimal.countryOfOrigin = @"NoIdeaHahahah";
// You can hardcode a couple like that, and add them to your array used for your tableview data. Basically we just want some of your custom objects in an array, for your tableview.
}
好的,现在我们有一个 Animal 数组(我们的数据)用于您的 tableview。您可以使用它来创建行。
在 cellForRow
中创建单元格时,只需从 :
Animal *animal = [myArray objectAtIndex:indexPath.row];
然后用该动物的特性喂养你的细胞
cell.titleLabel.text = animal.name;
例如。
并且在 didSelect
中,您可以修改特定的动物,就像我在这个答案的开头所说的那样:)
Animal *animal = [myArray objectAtIndex:indexPath.row];
animal.name = @"IJustChangedTheName";
[self.tableView reloadData];
所有这些都是常见的做法,除了我们在 viewDidLoad
中所做的非常残酷,但我相信您将能够根据您的代码进行调整:)
关于ios - 如何永久更改选定的单元格数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373122/