简体   繁体   中英

UIView doesn't seem to be remembering its tag

I'm using CPPicker to implement a horizontal picker in my application, and I'm using tags to figure out which of my two pickers I'm talking about.

     // Picker creation
     CPPickerView *pickerView = [[CPPickerView alloc] initWithFrame:CGRectMake(100, 5, 150, 40)];
     pickerView.dataSource = self;
     pickerView.delegate = self;
     pickerView.peekInset = UIEdgeInsetsMake(0, 40, 0, 40);
     [pickerView reloadData];
     pickerView.showGlass = YES;
     [cell addSubview:pickerView];

    if (indexPath.section == 0) {
        pickerView.tag = 0;
    }
    else if (indexPath.section == 1) {
        pickerView.tag = 1;
    }

    return cell;

Then later, I check the tag to specify the title for the pickerView. But it only ever reads 0 for the tag, so both pickers have the same value.

- (NSString *)pickerView:(CPPickerView *)pickerView titleForItem:(NSInteger)item {
    NSString *title = nil;

    if (pickerView.tag == 0) {
        title = [NSString stringWithFormat:@"%d", (200 + (item * 20))];
    }
    else if (pickerView.tag == 1) {
        title = [NSString stringWithFormat:@"%d", item + 1];
    }

    return title;
}

What am I doing wrong here?

Are you declaring picker view in a method or function. This would mean that it's not visible in another method or function. You might need to make it a property or at least declare it in you class extension as an instance variable.

The default value of a tag is zero, it might be better to start the tag count at 1, then you will be able to tell if it's getting set elsewhere or not getting set correctly.

if (indexPath.section == 0) {
    pickerView.tag = 1;
}
else if (indexPath.section == 1) {
    pickerView.tag = 2;
}

You're setting the tag to the pickerView, after you add it to the view. The pickerView on the view is now a copy of the original instance. Move the tag code above the addSubView call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM