如何判断 UITableViewCell
内的 UISwitch
何时被点击?
我的 UISwitch
在单元(通用单元)内部设置如下:
UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[cell addSubview:mySwitch];
cell.accessoryView = mySwitch;
我正在尝试检测这样的点击(但它不起作用):
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSUserDefaults *prefs;
if(indexPath.section == 1){
switch(indexPath.row)
{
case 0:
NSLog(@"Tapped Login Switch");
break;
default:
break;
}
}
}
Dave DeLong 建议我为每个开关设置一个操作作为解决方案。所以我执行了以下操作来设置开关:
UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[mySwitch addTarget:self action:@selector(switchToggled2:) forControlEvents: UIControlEventTouchUpInside];
if(at_songs){
[mySwitch setOn:YES animated:NO];
}
[cell addSubview:mySwitch];
cell.accessoryView = mySwitch;
通过以下信息可以了解何时被点击:
-(IBAction)switchToggled1:(id)sender {
NSUserDefaults *prefs;
NSLog(@"Tapped Login Switch");
prefs = [NSUserDefaults standardUserDefaults];
if(at_login){
[prefs setObject:@"NO" forKey:@"autotweet_login"];
at_login = NO;
}else{
[prefs setObject:@"YES" forKey:@"autotweet_login"];
at_login = YES;
}
}
打开开关不是问题。现在的问题是,当 UISwitch 设置为 OFF 时,由于某种原因,它的操作会被调用两次(我点击 1 次就会得到 2 个 NSLog)。
为什么只需轻按一下即可关闭开关,该操作就会被调用两次?我该如何修复它?
最佳答案
为开关指定目标和操作:
[mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventTouchUpInside];
然后实现你的 switchToggled: 方法:
- (void) switchToggled:(id)sender {
//a switch was toggled.
//maybe use it's tag property to figure out which one
}
关于iphone - 如何判断 UITableViewCell 内的 UISwitch 何时被点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2528535/