2009-02-22 128 views
8

如何正確對齊UIPickerView中的文本?我試圖爲行視圖定製UILabel,但由於某種原因,沒有任何內容顯示,右對齊或其他方式。這是我寫的:在UIPickerView中對齊文本

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { 
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero]; 
    [label setText:[NSString stringWithFormat:@"row %d", row]]; 
    [label setTextAlignment:UITextAlignmentRight]; 
    return [label autorelease]; 
} 

如果你想知道,我用CGRectZero因爲我看到它在UICatalog例子。

回答

3

由於CGRectZero你沒有看到任何東西。你需要在你的情況下設置一個大小。

在UICatalog中,如果您談論他們如何將CGRectZero用於CustomView ...以及如果您查看CustomView.m,您將看到它們實際上忽略了CGRectZero並在initWithFrame中將框架設置爲一個大小:

0

確保您:

  • 提供一個明確的框架,該框架爲高和寬的需求;
  • 適當設置標籤的顯示不透明度(通過.opaque = YES或NO)和背景顏色(通常分別需要NO和[UIColor clearColor])。
  • 顯式設置字體。
8

我在picker和兩個數組中使用了兩個組件來設置特定組件中行的標題。

下面的代碼將在picker數據中心顯示picker的默認字體和字體大小。 它將給picker數據的中心對齊提供確切的picker數據顯示行爲。

這裏,

NSArray *component1Array=[NSArray arrayWithObjects:@"0 lbs",@"1 lbs",@"2 lbs",@"3 lbs",@"4 lbs",@"5 lbs",nil]; 

NSArray *component2Array=[NSArray arrayWithObjects:@"0.00 oz",@"0.25 oz",@"0.50 oz",@"0.75 oz",@"1.00 oz",nil]; 

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
     { 
      //I have taken two components thats why I have set frame of my "label" accordingly. you can set the frame of the label depends on number of components you have... 

      UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 145, 45)]; 

      //For right alignment of text,You can set the UITextAlignmentRight of the label. 
      //No need to set alignment to UITextAlignmentLeft because it is defaulted to picker data display behavior. 

      [label setTextAlignment:UITextAlignmentCenter]; 
      label.opaque=NO; 
      label.backgroundColor=[UIColor clearColor]; 
      label.textColor = [UIColor blackColor]; 
      UIFont *font = [UIFont boldSystemFontOfSize:20]; 
      label.font = font; 
      if(component == 0) 
      { 
       [label setText:[NSString stringWithFormat:@"%@",[component1Array objectAtIndex:row]]]; 
      } 
      else if(component == 1) 
      { 
       [label setText:[NSString stringWithFormat:@"%@", [component2Array objectAtIndex:row]]]; 
      } 
      return [label autorelease]; 
     } 

你應該低於一提UIPickerView委託的方法,如果您使用上述方法評論...

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

以上示例代碼的輸出將類似於下面

alt text