我有一个带有 UISwitchs
的 UITableView
。
切换开关后,我想运行一个函数。该功能仅记录开关是否打开或关闭以及开关已更改的行。我遇到的问题是,当我单击开关时,它不会记录正确的行,除非我在单击开关之前单击了该行。
我想我的问题是点击开关没有选择行。我怎样才能让它选择行或者我可以将 ID 添加到开关?
因此开关 ID“1”为“ON”。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"POICell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//set the cell text to the catName
cell.textLabel.text = [self.catNames objectAtIndex:[indexPath row]];
//add switch
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;
[switchView setOn:YES animated:NO];
[switchView addTarget:self action:@selector(switchChanged: ) forControlEvents:UIControlEventValueChanged];
// Configure the cell...
return cell;
}
- (void) switchChanged:(id)sender {
NSString *StrCatID =[[NSString alloc]init];
StrCatID = [self.catIDs objectAtIndex:[self.inputTableView indexPathForSelectedRow].row];
UISwitch* switchControl = sender;
NSLog( @"The switch for item %@ is %@",StrCatID, switchControl.on ? @"ON" : @"OFF" );
}
最佳答案
找到持有开关的单元格
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
找到该单元格的索引路径
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
你的情况
- (void) switchChanged:(id)sender {
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
NSString *strCatID =[[NSString alloc]init];
strCatID = [self.catIDs objectAtIndex:indexpath];
NSLog( @"The switch for item %@ is %@",StrCatID, switchInCell.on ? @"ON" : @"OFF" );
}
关于iphone - 单击 UISwitch 时选择 UITableView 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13121139/