UIPickerView 内容意外流动

UIPickerView content flowing unexpectedly

我在我的应用程序中使用 UIDatePickerUIPickerView。但是两个控件都显示出奇怪的行为。当我滚动选择器中的内容时,它会流到选择器之外并且不会按预期滚动。我的实现如下。

sexArray = @[@"Male", @"Female"];
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 50, 100, 150)];
[picker setDataSource: self];
[picker setDelegate: self];
picker.showsSelectionIndicator = YES;
genderTF.inputView = picker;


#pragma mark -- UIPICKERVIEW METHODS

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return sexArray.count;
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
      forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *retval = (UILabel*)view;
if (!retval) {
    retval = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100, [pickerView rowSizeForComponent:component].height)];
}

retval.font = [UIFont fontWithName:@"SourceSansPro-Regular" size:15.0f];
retval.minimumScaleFactor = 0.6;
[retval setTextAlignment:NSTextAlignmentCenter];
retval.text = [sexArray objectAtIndex:row];

return retval;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
[genderTF setText:sexArray[component]];
}

当在另一个应用程序中使用相同的代码(用于测试)时,它按预期工作。

您需要实施 titleForRow 而不是 viewForRow

 -(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{


return [sexArray objectAtIndex:row];

 }

更新:

如果您将选择器视图用作 textfieldinput view,则不要使用框架初始化它。

初始化选择器视图,

UIPickerView *picker = [[UIPickerView alloc] init];

希望这会有所帮助:)

事实证明,我的实施是正确的。问题是因为第三方库。

我在我的项目中使用了一个 pod SLPagingView,这使得“UIPickerView”表现得很奇怪。我找不到解决方案,最终用类似的 pod 替换了 pod。

详情link

我发现这个问题是因为我用了一个叫"SLPagingView"的第三方库,不知道你有没有用。 如果你这样做了,这可能会有所帮助。我刚刚通过修改 "UIScrollView+UpdateContentSize.m" 文件中的 -(void)setFrame:(CGRect)frame 和 -(void)updateConstraints 方法解决了这个问题,这是我的代码:

#pragma mark - OVERRIDE
-(void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    // Scale the content size
    Class UIPickerTableView = NSClassFromString(@"UIPickerTableView");
    if ([self class] == UIPickerTableView) {
        return;
    }else {
        [self updateContentSize];
    }
}

-(void)updateConstraints {
    [super updateConstraints];
    // Scale the content size
    Class UIPickerTableView = NSClassFromString(@"UIPickerTableView");
    if ([self class] == UIPickerTableView) {
        return;
    }else {
        [self updateContentSize];
    }
}

这个有用,希望它也能帮到你。