如果拖动UISwitch不工作

时间:2014-05-06 13:05:21

标签: ios xcode uiswitch

我在UISwitch内添加contentview作为UITableViewCell

控件仅在轻敲时有效,但如果我尝试将其向左或向右拖动,则不会调用选择器功能。

任何帮助?

4 个答案:

答案 0 :(得分:2)

switch_Bool = [[UISwitch alloc]initWithFrame:CGRectMake(0,0,20,20)];
[switch_Bool addTarget:self action:@selector(actionBoolSwitch:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:switch_Bool];

仅当我点击我的UISwitch时才有效,但是如果我拖动它,则不会调用函数actionBoolSwitch ...

答案 1 :(得分:1)

我从您的问题中了解到,您正在尝试将UiSwitch添加到表格视图单元格。

作为标准做法,您需要做的第一件事是创建UITableViewCell的子类,添加所需的所有组件,然后在cellForRowAtIndexPath中使用它。

  
    

看看下面的示例代码。

  
  //inside your cell creation block


    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(add coordinates here...)];
    [mySwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
    mySwitch.tag = indexpath.row;
    [cell.contentview addSubview:mySwitch];

  }

  - (void)changeSwitch:(id)sender{

   if([sender isOn])
    {
      NSLog(@"Switch is ON");
    } 
   else
   {
    NSLog(@"Switch is OFF");
   }

 }

Also take a look at this link

答案 2 :(得分:1)

您可能正在使用UIControlEventTouchUpInside事件。 请改用UIControlEventValueChanged,以便每次UISwitch值更改时都会调用您的操作,无论触发器是什么事件。

答案 3 :(得分:-2)

试试这个。

查找包含开关的单元格

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" );
        }