单击UISwitch时选择UITableView的行 [英] Select UITableView's row when clicking on UISwitch

查看:89
本文介绍了单击UISwitch时选择UITableView的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 UITableView ,上面带有 UISwitchs

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

When the switch is toggled I want to run a function. The function just logs If the switch is on or off and the row that the switch has been changed on. The problem that im having is that when I click on the switch it does not log the correct row unless I have clicked on that row before clicking the switch.

我想我的问题是单击开关不会选择行。我怎样才能使它选择行或者我可以将ID添加到交换机?

I guess my problem is that clicking the switch does not select the row. How can I make it so that it either selects the row or can I add the ID to the switch?

所以开关ID1为ON。

So switch ID "1" is "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" );
        }

这篇关于单击UISwitch时选择UITableView的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆