Multiple line of text in UIPickerView

UIPickerView is a user interface component available from iOS 2.0 and above.

The basic need of UIPickerView is to select any one option from the list of data that are loaded to the picker view. But, by default, only one line of text is allowed to be displayed in a UIPickerView.

Today, we will try to add multi-line text to an UIPickerView. To do so, we need to implement the viewForComponent api.  

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view;

In that method, type cast the view parameter to an UILabel.

   UILabel *pickerLabel = (UILabel *)view;

Update the frame size of the label.

   CGRect frame = CGRectMake(0,0,265,40);
   pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];

Set the properties of the label as per requirement.

   [pickerLabel setTextAlignment:UITextAlignmentLeft];
   [pickerLabel setBackgroundColor:[UIColor clearColor]];
   [pickerLabel setFont:[UIFont boldSystemFontOfSize:12.0]];
   [pickerLabel setNumberOfLines:0];
   [pickerLabel setText:@"dynamic text from an array or dictionary"];


Return the UILabel to the PickerView.
   return pickerLabel;

Now, the UIPickerView label will contain multiple line of text.

The consolidated code from the above steps  will look like,

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
      
      UILabel *pickerLabel = (UILabel *)view;
      CGRect frame = CGRectMake(0,0,265,40);
      pickerLabel = [[[UILabel allocinitWithFrame:frame] autorelease];
      [pickerLabel setTextAlignment:UITextAlignmentLeft];
      [pickerLabel setBackgroundColor:[UIColor clearColor]];
      [pickerLabel setFont:[UIFont boldSystemFontOfSize:12.0]];
      [pickerLabel setNumberOfLines:0];
      [pickerLabel setText:@"dynamic text from an array or dictionary"];
      return pickerLabel;
}


And, ONE MORE THING,
Since the height of the PickerView Label is limited, you can have two lines of text. 
More than two lines won't be visible to the user in Picker view. If needed, try to adjust the font size of the text assigned

Comments

  1. Thanks for this! Very helpful!

    ReplyDelete
  2. Thanks its helpful me too.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. You should use some special container for the code. It is very hard to read it this way. Thank you anyways.

    ReplyDelete

Post a Comment

Popular posts from this blog

Connect Samsung devices to Kies on Mac

Integrating ZXing QR Code reader in iPhone / iOS applications