2008-11-02 79 views
15

我有以下代碼來創建一個UIPickerView:如何更改UIPickerView的文本大小和組件寬度?

pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0f, 416.0f - height, 320.0f, height)]; 
pickerView.delegate = self; 
pickerView.showsSelectionIndicator = YES; 
[pickerView setSoundsEnabled:YES]; 

我想更改組件的寬度和每個組件改變文字大小。是否有可能做到這一點?

謝謝!

回答

50

您可以通過適當的委託方法更改寬度

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { 
    switch(component) { 
     case 0: return 22; 
     case 1: return 44; 
     case 2: return 88; 
     default: return 22; 
    } 

    //NOT REACHED 
    return 22; 
} 

對於自定義文本大小,您可以使用委託與你想要的任何大小的文本返回自定義視圖:

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

     retval.text = @"Demo"; 
     retval.font = [UIFont systemFontOfSize:22]; 
     return retval; 
} 

當然,您將需要修改這些以爲您的應用程序提供適當的值,但它應該會將您帶到需要去的地方。

+0

您的第二個代碼塊中有幾個錯誤: \t - UIView需要轉換爲(UILabel *)。 \t - retval賦值行缺少左括號,需要調用initWithFrame,否則我們不會顯示任何內容: ie。 \t retval = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f,0.0f,[pickerView rowSizeForComponent:component] .width,[pickerView rowSizeForComponent:component] .height)] autorelease]; – 2010-03-16 02:58:37

相關問題