你今天过得怎么样,希望一切顺利
我的问题是我在 uitableviewcell 中有 uiswitch 。但是,当我使用 contentview 将开关添加为单元格中的子视图时,它不会出现在我的单元格上吗?请问有人知道为什么它们没有出现在每个自定义单元格上吗?提前致谢 。
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
UISwitch *switchController = nil ;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"Cell"];
switchController= [[UISwitch alloc] initWithFrame:CGRectZero];
switchController.tag=100;
[cell.contentView addSubview:switchController];
CGRect switchFrame = switchController.frame;
switchFrame.origin.x = 50.0f;
switchFrame.origin.y = 10.0f;
switchController.frame = switchFrame;
[switchController addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
}
else
{
switchController =(UISwitch *)[cell.contentView viewWithTag:100];
}
//This for persist switch state when scroll up or down
if ([[[self.SwitchArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row ]isEqualToString:@"ON"])
{
switchController.on=YES;
}
else
{
switchController.on=NO;
}
NSString *value = [[mainArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = value;
cell.textLabel.textAlignment = NSTextAlignmentRight;
cell.textLabel.font = [UIFont systemFontOfSize:15.0];
return cell;
}
这是 SwitchChanged 的代码:
-(void)switchChanged:(UISwitch *)sender
{
UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *index=[mainTableView indexPathForCell:cell];
if (sender.on)
{
[[self.SwitchArray objectAtIndex:index.section] replaceObjectAtIndex:index.row withObject:@"ON"];
}
else
{
//Update my switch states array
[[self.SwitchArray objectAtIndex:index.section] replaceObjectAtIndex:index.row withObject:@"OFF"];
}
[padFactoids setObject:[NSKeyedArchiver archivedDataWithRootObject:SwitchArray] forKey:@"savedArray"];
[padFactoids synchronize];
}