我在uitableviewcontroller中使用不同的原型单元。它工作正常,除非使用UISwitches。如果我使用许多UISwitch并切换了一个开关,则其他的Switch也被切换。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict;
if (indexPath.row > 0) {
dict = [self.fieldsArray objectAtIndex:indexPath.row-1];
int nr = [[dict objectForKey:@"typeid"] intValue];
if (nr == 1) {
//cell with in texfield
} else if (nr == 2) {
static NSString *CellIdentifier2 = @"switch";
UITableViewCell *cell = [self.ficheTableView dequeueReusableCellWithIdentifier:CellIdentifier2 forIndexPath:indexPath];
cell.textLabel.text = @"";
[self createLabelWithCell:cell tag:1 dict:dict valuekey:@"label" indexpath:indexPath];
UISwitch *switch1 = (UISwitch *)[cell viewWithTag:2];
switch1.tag = [[dict valueForKey:@"id"] integerValue];
switch1.accessibilityIdentifier = @"value";
switch1.on = NO;
if ([dict valueForKey:@"value"] != [NSNull null]) {
if ([[dict valueForKey:@"value"] isEqualToString:@"1"]) {
NSLog(@"%ld %@",(long)switch1.tag, [dict valueForKey:@"value"]);
switch1.on = YES;
}
}
[switch1 addTarget: self action: @selector(flipSwitch:) forControlEvents:UIControlEventValueChanged];
return cell;
} else if (nr == 3) {
//cell with a textfield number only
}
...
}
- (IBAction)flipSwitch:(id)sender {
UISwitch *switch2 = (UISwitch*)sender;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *aValue;
NSString *tag = [NSString stringWithFormat:@"%ld",(long)switch2.tag];
NSString *userid = [userDefaults stringForKey:kuserid];
if (switch2.on) aValue = @"1"; else aValue = @"0";
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
switch2.accessibilityIdentifier,@"field",
tag,@"id",
aValue,@"value",
@"BLABLA",@"appcode",
userid,@"userid",
@"updatefichenr", @"command",
nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:appDelegate.baseURLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
}
如果我在放置在较低位置的UISwitch的flipSwitch中读取标签,我还将获得其他UISwitch的标签。
我已经在这里查看过类似的问题,但没有找到解决问题的方法。
您的方法是错误的。如果您的表视图单元是动态的(基于值更改的用户操作),则需要采用自定义单元类。需要给子视图提供出口。在单元格中给出
swith.tag = indexpath.row;
使用此标签,您可以重新加载特定的单元格。