UIPIckerView显示奇怪的行为

时间:2014-07-30 06:18:36

标签: ios objective-c uipickerview

我是iOS开发的新手,我有一个任务,我需要实现一个UITextfield,点击它,带来一个国家选择器UIPickerView。

我经历了一些在线教程,并以某种方式让它工作。但它显示了一些我似乎无法弄清楚的奇怪行为。

出现了一些奇怪的黑条,每次滚动时选择器内容都会明显重复。

我相信我在代码中犯了一个错误,原谅我缺乏知识,但似乎无法弄清楚代码中的错误。

你能告诉我出了什么问题吗?

enter image description here

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if ([textField isEqual:self.countryTextField]) {
        countryPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
        countryPicker.showsSelectionIndicator = YES;
        self.countryPicker.delegate = self;
        self.countryPicker.dataSource = self;
       // [self.countryPicker reloadAllComponents];
       countryPicker.showsSelectionIndicator = YES;
   //     [countryPicker init:self];

        textField.inputView = countryPicker;
    }

    return YES;
}

- (UIView * ) pickerView: (UIPickerView * ) pickerView viewForRow: (NSInteger) row forComponent: (NSInteger) component reusingView: (UIView * ) view {


        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
    label.text =   [NSString stringWithFormat:@"%@", [[self.countries objectAtIndex:row] objectForKey:@"name"]];


    [label setTextAlignment:UITextAlignmentLeft];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setFont:[UIFont boldSystemFontOfSize:15]];

        return label;
    }

3 个答案:

答案 0 :(得分:0)

似乎代码中很少有东西需要更改 1.每次编辑文本字段时都不要为UIPickerView分配内存-textFieldShouldBeginEditing

if(self.countryPicker == nil)
{
   self.countryPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
   self.countryPicker.showsSelectionIndicator = YES;
    self.countryPicker.delegate = self;
    self.countryPicker.dataSource = self;
   self.countryPicker.showsSelectionIndicator = YES;
}

2.使用self.countrypicker - > class属性或countrypicker不会互换使用它们。

答案 1 :(得分:0)

每次都可以初始化,而不是每次初始化,检查UIPicker是否已经初始化

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if ([textField isEqual:self.countryTextField]) {

       if(! countryPicker){
        countryPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
        countryPicker.showsSelectionIndicator = YES;
        self.countryPicker.delegate = self;
        self.countryPicker.dataSource = self;
        countryPicker.showsSelectionIndicator = YES;
       }
        textField.inputView = countryPicker;
    }

    return YES;
}

答案 2 :(得分:0)

好吧,我终于找到了这个问题。在numberOfComponentsInPickerView

中定义错误数量的组件是一个愚蠢的错误