ios - 如何为 UISwitch 设置/获取标签值 (NSInteger)

标签 ios objective-c

我有使用 for 循环创建的动态 UISwitches。我为每个控件赋予标签值以具有标识。后面想达到这些值,但是每次都得到0。我做错了什么?

for(int i = 0;i < self.extraArray.count; i++) {

    ProductPropertiesModel *model = (ProductPropertiesModel *)[self.extraArray objectAtIndex:i];

    UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectZero];    
    switchButton.translatesAutoresizingMaskIntoConstraints = false;    
    switchButton.tag = [model Id];    
    [switchButton setOn:NO];    
    [self.view addSubview:switchButton];    
    [switchButton addTarget:self action:@selector(setState:)
           forControlEvents:UIControlEventValueChanged];

}

-(void)setState:(id)sender
{

    UISwitch *uiswitch = (UISwitch *)sender;    
    NSInteger tagInteger= uiswitch.tag;    
    NSLog(@"%@", [NSString stringWithFormat:@"%li",(long)tagInteger]);

}

标签值为0,但这是错误的。

最佳答案

我发现了问题。我刚刚打错字了。我发现我在获取json数据时写错了。我注意到写的是 Id 而不是 id。

NSError *jsonError;
        self.extraJsonArray = nil;
        self.extraJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
        self.extraArray = [[NSMutableArray alloc]init];
        for(int j = 0;j < self.extraJsonArray.count;j++){
            @try {
                //NSInteger *Id = (NSInteger *)[(NSNumber *)[[self.extraJsonArray objectAtIndex:j]objectForKey:@"Id"] integerValue]; Problem is here
                NSInteger *Id = (NSInteger *)[(NSNumber *)[[self.extraJsonArray objectAtIndex:j]objectForKey:@"id"] integerValue];
                double price = (double)[(NSNumber *)[[self.extraJsonArray objectAtIndex:j] objectForKey:@"price"] doubleValue];
                NSString *property =(NSString *)[[self.extraJsonArray objectAtIndex:j] objectForKey:@"property"];
                ProductPropertiesModel *model = [[ProductPropertiesModel alloc] init];
                [model setId:Id];
                [model setProperty:property];
                [model setPrice:price]; 
                [model setChecked:@"No"];
                [self.extraArray addObject:model];
            } @catch (NSException *exception) {
                NSLog(@"%@", exception.reason);
            } @finally {

            }
        }

关于ios - 如何为 UISwitch 设置/获取标签值 (NSInteger),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55649892/

相关文章:

ios - TabBar 图像的大小应该是多少?

ios - 在 iOS 11.2 上预览 PDF 文件

ios - UIViewPagerController 与 UIScrollView 中的动态高度 Controller

ios - 如何在ios中的另一个类中获取NSDictionary JSON数据

ios - 如何将一个类的函数访问到另一个 objective-c

iphone - 使用 NSPredicate 获取核心数据对象的问题

iOS:无法在 UITableViewCell 中使用 Activity Indicator

objective-c - UIScrollView 不使用自动布局约束

objective-c - 复杂的CATransition

ios - 是否可以将状态栏的字体颜色更改为自定义颜色?