iphone - 单击 UISwitch 时选择 UITableView 的行

标签 iphone objective-c ios xcode

我有一个带有 UISwitchsUITableView

TableView

切换开关后,我想运行一个函数。该功能仅记录开关是否打开或关闭以及开关已更改的行。我遇到的问题是,当我单击开关时,它不会记录正确的行,除非我在单击开关之前单击了该行。

我想我的问题是点击开关没有选择行。我怎样才能让它选择行或者我可以将 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/

相关文章:

iOS - 手机锁定时显示 View

objective-c - cocoa : is there a way to know if the user has set "Set date & time automatically" in system preferences?

ios - UILabel 中的尺寸和线条问题

ios - AFNetworking - 数据已加载,但出现错误 504

ios - 如何在 MAC 机器中从命令提示符启动 Appium 服务器?

ios - 在 Objective-c 项目中添加第二个 swift 文件没有效果

iPhone WebKit CSS 动画导致闪烁

iphone - 尝试发布到应用商店 - 未连接已配置的 iOS 设备

iphone - 从 NSMutableArray 获取记录时 Indexpath.row 不工作

ios - 生成其他节点后旋转停止