2009-02-22 119 views
8

UIPickerViewのテキストを右揃えにするにはどうすればよいですか?私は行ビューのためにカスタムUILabelを作成しようとしましたが、何らかの理由で何も表示されず、右揃えになっていません。ここで私が書いたものだ:私はUICatalog例でそれを見たので、誰もが疑問に思っている場合には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を使用しました。

答えて

3

CGRectZeroのため何も見えません。あなたのケースにサイズを設定する必要があります。

あなたがCustomView.mを見てもCGRectZeroを使ってCGRectZeroをどのように使用していたのかを知っていれば、実際にはCGRectZeroを無視してフレームをinitWithFrameのサイズに設定しています。

0

ご確認してください:

  • が必要なだけ高くかつ広い明示的なフレームを提供します。
  • ラベルの表示の不透明度(.opaque = YESまたはNO)と背景色を適切に設定します(通常、それぞれNOと[UIColor clearColor]が必要です)。
  • フォントを明示的に設定します。
8

特定のコンポーネントの行のタイトルを設定するために、ピッカーと2つのコンポーネントで2つのコンポーネントを使用しました。

以下のコードはピッカーのデフォルトフォントとフォントサイズを中心にピッカーデータを中央に表示します。 これは、ピッカーデータの中心の位置合わせを伴う正確なピッカーデータの表示動作を与える。ここで

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

3

iOS 6では、テキスト整列属性を含むことができるNSAttributedStringを返します。他の関連する質問の短いスニペットを投稿しました:https://stackoverflow.com/a/14035356/928963