【问题标题】:UISwitch not working if dragged如果拖动 UISwitch 不起作用
【发布时间】:2014-06-23 02:49:14
【问题描述】:

我在UITableViewCell 中添加了一个UISwitch 作为contentview

该控件仅在被点击时才起作用,但如果我尝试将其向左或向右拖动,则不会调用选择器函数。

有什么帮助吗?

【问题讨论】:

  • 你添加了什么作为目标控制事件?
  • 让我们看看一些代码。如果我们看不到代码,我们将无能为力。
  • 请贴出您尝试过的代码,这有助于相应地回答。
  • UISwitch 在拖动时不会发送更改事件,只有在拖动后释放其句柄时才会发送它的状态。

标签: ios xcode uiswitch


【解决方案1】:
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 不会被调用...

【讨论】:

    【解决方案2】:

    我从您的问题中了解到,您正在尝试将 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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        试试这个。

        找到持有开关的单元格

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

        【讨论】:

          猜你喜欢
          • 2015-08-03
          • 1970-01-01
          • 1970-01-01
          • 2018-03-14
          • 1970-01-01
          • 1970-01-01
          • 2015-08-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多