Thursday, July 1, 2010

iPhone : Change font and label size in UIPIckerView

while using picker view in iPhone ,I face the challenge how to re size the text appearing in Picker view components.

Just do it!
Instead of using-

- (NSString *) pickerView:(UIPickerView *) pickerView

titleForRow:(NSInteger) row

forComponent:(NSInteger) component

{

}



//USE



- (UIView *)pickerView:(UIPickerView *)pickerView

viewForRow:(NSInteger)row

forComponent:(NSInteger)component

reusingView:(UIView *)view {

UILabel *pickerLabel = (UILabel *)view;

if (pickerLabel == nil) {
//label size
CGRect frame = CGRectMake(0.0, 0.0, 70, 30);

pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];

[pickerLabel setTextAlignment:UITextAlignmentLeft];

[pickerLabel setBackgroundColor:[UIColor clearColor]];
//here you can play with fonts
[pickerLabel setFont:[UIFont fontWithName:@"Times New Roman" size:14.0]];

}
//picker view array is the datasource
[pickerLabel setText:[pickerViewArray objectAtIndex:row]];

return pickerLabel;

}

Garg Praveen

5 comments:

  1. Thnks Praveen..it worked..

    ReplyDelete
  2. tanks ..it worked for me too..very nicely explained.

    ReplyDelete
  3. hi praveen,This is Gajendra from ahmedabad.I'm working as iPhone developer,
    I need to populate picker view data updated while calling xml,soap webservice. e.g : I have 1 picker view with 2 component 1 for categories and 2 for sub-categories.Using web service how to call this method.If u have any idea share with me on gk_chauhan2008@yahoo.com / gkchauhan6750@gmail.com

    ReplyDelete
  4. @Gajendrasinh

    Let me proceed with basic concept:

    Picker view populates with datasource (that is an array of objects).

    //picker view array is the datasource
    [pickerLabel setText:[pickerViewArray objectAtIndex:row]];

    1) Parse SOAP object (XML response) and create datasource array (that may have object of datatype NSDictionary with category name as key and subcategory array as value of dictionary object).

    2) In delegate method

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


    Here component defines for what component, you need which data to be populated. so you can put if/else in the code. To distinguish between components, you can check using if/else.
    and then can populate the subcategory(ies) with dictionary object values.

    Hope this helps!

    ReplyDelete
  5. Thank you very much, Praveen!

    I appreciate you taking the time to post this - I found it very useful!

    -Roger

    P.S. I know this was posted well before iOS6, but UITextAlignmentLeft has been deprecated. Use NSTextAlignmentLeft.

    i.e.
    [pickerLabel setTextAlignment:NSTextAlignmentLeft];

    [pickerLabel setTextAlignment:NSTextAlignmentLeft];

    ReplyDelete