简体   繁体   English

UIView似乎不记得它的标签

[英]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. 我正在使用CPPicker在应用程序中实现水平选择器,并且正在使用标签来确定我正在谈论的两个选择器中的哪一个。

     // 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. 然后,我检查标签以指定pickerView的标题。 But it only ever reads 0 for the tag, so both pickers have the same value. 但是它只会读取0,因此两个选择器的值相同。

- (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. 标签的默认值为零,最好将标签计数从1开始, 然后您将能够知道它是在其他位置设置还是未正确设置。

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. 在将标签添加到视图之后,将其设置为pickerView。 The pickerView on the view is now a copy of the original instance. 现在,视图上的pickerView是原始实例的副本。 Move the tag code above the addSubView call 将标记代码移到addSubView调用上方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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