如何设置/获取UISwitch的标签值(NSInteger)

时间:2019-04-12 10:45:45

标签: 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,但这是错误的。

3 个答案:

答案 0 :(得分:1)

我建议改为将[model id]设置为标签,而应将数组索引设置为标签。

然后在切换控制方法中,您可以使用代码从数组索引中获取值。

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

希望这会有所帮助。

答案 1 :(得分:0)

尝试一下:

SELECT DATE(TIMESTAMP_FORMAT(CHAR("tablename"."date"),'YYMMDD')) 
FROM tableName
OFFSET 10 ROWS

答案 2 :(得分: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 {

            }
        }