UIPickerView的组件宽度是否可以手动调整?

时间:2012-09-24 22:09:06

标签: objective-c

我制作了UIPickerView并添加到viewcontroller'view。

我手动调整了pickerview'width。

当您查看图片时,组件的内容宽度和组件宽度之间不匹配,

pickerview的宽度和组件宽度。

是否有像UILabel的sizeToFit这样的方法?

expected code is :
    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
        switch(component) {
            [pickerView.label sizeToFit];
        }
    }


================= Following is mycode ====================================================
- (void)viewDidLoad {

    self.view.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];

    [super viewDidLoad];

    UIPickerView *pickerView = [[[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)] autorelease];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    pickerView.showsSelectionIndicator = YES;

    [self.view addSubview:pickerView];


    activities = [[NSArray alloc] initWithObjects:@"sleeping", @"eating", @"working", @"studying", @"walking", @"thinking", @"considering", @"testing", @"talking", nil];
    feelings = [[NSArray alloc] initWithObjects:@"awesome", @"sad", @"happy", nil];

}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    switch(component) {
        case 0: return 100;
        case 1: return 200;
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试我的解决方案..我从来没有设置宽度&每个组件的高度... UIPickerview维护自己...所以我不必担心这个....尝试这只是注释称为“widthForComponent”的整个方法,并确保你已经使用了所有这些Picker方法。 。“numberOfComponentsInPickerView”,“numberOfRowsInComponent”和“titleForRow”再次运行项目...让我知道它会解决你的问题

好了现在看到uipickerview需要以下方法......你想要一些代码,然后在这里

- (void)pickerView:(UIPickerView *)pV didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // you're code for when user select any item from picker
}

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

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{ 
    if(component == 0)
        return [activities count];
    else if(component == 1)
        return [feelings count];
    
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0)
        return [activities objectAtIndex:row];
    else if(component == 1)
        return [feelings objectAtIndex:row];
    else
           return @"";
}