Customise The Appearance Of Uipickeview

2012-12-19

Sometimes we left the UIPickerView in plain vanilla design without attempting to customise it. It’s easy and it gives a whole different feeling if you had already change the appearance of view controllers. For the beginning - lets say that we want to change the font, We have to use a UIPickerViewDelegate method like: [sourcecode language=“objc”] - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view [/sourcecode] and more precisely: [sourcecode language=“objc”] - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *pickerViewLabel = (id)view; if (!pickerViewLabel) { pickerViewLabel= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width - 10.0f, [pickerView rowSizeForComponent:component].height)]; } pickerViewLabel.backgroundColor = [UIColor clearColor]; pickerViewLabel.text = therapyTypes[row]; // where therapyTypes[row] is a specific example from my code pickerViewLabel.font = [UIFont fontWithName:@“ChalkboardSE-Regular” size:20]; return pickerViewLabel; } [/sourcecode] And after that we get the usual picker view with different font. What if we want to add an image in front of every label like the following screenshot: [caption id=“attachment_196” align=“aligncenter” width=“300”]customise UIPickerView customise UIPickerView[/caption] then we have to modify the above code like: [sourcecode language=“objc”] - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UIView *pickerCustomView = (id)view; UILabel *pickerViewLabel; UIImageView *pickerImageView; if (!pickerCustomView) { pickerCustomView= [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width - 10.0f, [pickerView rowSizeForComponent:component].height)]; pickerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 35.0f, 35.0f)]; pickerViewLabel= [[UILabel alloc] initWithFrame:CGRectMake(37.0f, -5.0f, [pickerView rowSizeForComponent:component].width - 10.0f, [pickerView rowSizeForComponent:component].height)]; // the values for x and y are specific for my example [pickerCustomView addSubview:pickerImageView]; [pickerCustomView addSubview:pickerViewLabel]; } pickerImageView.image = [self selectTherapyImageFor:therapyTypes[row]]; pickerViewLabel.backgroundColor = [UIColor clearColor]; pickerViewLabel.text = therapyTypes[row]; // where therapyTypes[row] is a specific example from my code pickerViewLabel.font = [UIFont fontWithName:@“ChalkboardSE-Regular” size:20]; return pickerCustomView; } [/sourcecode] Easy and beautiful…