【发布时间】:2013-07-19 14:04:48
【问题描述】:
我是 iOS 编码的新手,我在 SO 中环顾四周并尝试了几种方法来解决这个问题,但似乎没有任何效果。我确信这是因为我的一些愚蠢的错误:-)
我有一个分区表,总共大约 25 行,分为 2 个部分。
每个cell.accessoryView 都有一个开关,我尝试在开关状态更改时将其存储在NSArray 中,但是在该索引处记录数组内容在任何情况下都会奇怪地返回0。
(数组被实例化为TableViewController的属性(nonatomic, readwrite),并合成)
显然,当我上下滚动表格时,所有开关都返回默认的OFF 状态。
感谢您的帮助!
- (void)viewDidLoad
{
[super viewDidLoad];
//countries dict and switch state array init..
self.countries = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"countries" ofType:@"plist"]];
NSNumber *b = [NSNumber numberWithBool:NO];
for (int i=0; i<210; i++) {
[statiSwitch addObject:b];
NSLog(@"%d", [[statiSwitch objectAtIndex:i] integerValue]);
}
//tableview drawing..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellWithSwitch";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *continent = [self tableView:tableView titleForHeaderInSection:indexPath.section];
NSString *country = [[self.countries valueForKey:continent] objectAtIndex:indexPath.row];
//Simple tag calculation...
NSInteger tagOb = indexPath.section * 100 + indexPath.row;
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[mySwitch addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
mySwitch.tag = tagOb;
if ([statiSwitch count] > tagOb) {
[mySwitch setOn:[[statiSwitch objectAtIndex:tagOb] boolValue] animated:NO];
}
cell.textLabel.text = country;
cell.accessoryView = mySwitch;
return cell;
}
然后是切换状态变化时调用的方法:
- (void) switchChange:(UISwitch *)sender {
NSNumber *c = [NSNumber numberWithBool:sender.on];
[statiSwitch replaceObjectAtIndex:sender.tag withObject:c];
NSLog(@"switch tag is: %i and state is: %d", sender.tag, sender.on);
NSLog(@"switch states array value: %d", [[statiSwitch objectAtIndex:sender.tag] integerValue]);
}
【问题讨论】:
-
尝试子类化 UITableViewCell,并将整个单元格存储在一个数组中,而不仅仅是开关值。然后,随着 tableView 滚动,将单元格拉出数组而不是出队。
-
那么,我应该设置一个包含所有(比方说)20 个单元对象的数组,包括附件开关,然后让
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法从该数组中取出单元?跨度> -
你应该继承 UITableViewCell,并在该类中处理切换操作。这就像使用对象类来存储数据一样。
-
好的,我试试看!谢谢! (如果您建议我为处理开关操作的子类提供一些示例代码.. 那会很棒:-)
-
您是在做故事板,还是全部用代码完成?使用故事板,这是一个非常简单的过程。
标签: ios uitableview xcode4.6 uiswitch accessoryview