我是iOS编程的新手,我在这里环顾了这里,并尝试了几种方法来解决这个问题,但似乎没有任何工作。我很确定这是因为我的一些愚蠢的错误:-)UISwitch在每个分区表行的附件查看
我有一个分节表,共约25行,分为2节。 每个cell.accessoryView
都有一个开关,我试图在NSArray
中存储开关状态,但是在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滚动时,将该单元格拉出数组而不是出队。 – AMayes
因此,我应该建立一个包含所有20个单元对象(包括附件开关)的数组,然后使用' - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath'方法从该数组中取出单元格? – Paolo83
你应该继承UITableViewCell,并处理该类中的开关动作。这就像使用对象类来存储数据一样。 – AMayes