I'm trying to create a UIPicker where I can select minutes and seconds. Here's the code:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if(component == 0)
return 24;
return 60;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 30;
}
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[paragraphStyle setTailIndent:20];
NSString *value = [NSString stringWithFormat:@"%d", row];
return [[NSAttributedString alloc] initWithString:value
attributes:@{NSParagraphStyleAttributeName:paragraphStyle}];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
return 160;
}
How can I get rid of the annoying curvature and just make vertical columns?
Also, how can I add "min" and "sec" to the selection row?
As others have said, the existing API can't do it. If you want to do this, you'll have to write your own code to do it. I created a horizontal value picker in the past and it was annoying, but fairly straight forward. To do it I used a
UILabel
, an image and aUIScrollView
.First set up the UI
Visually it show work... for the most part, but we need back end code to support it.
UIScrollViewDelegate
and implementscrollViewDidScroll:
which will tell you the content offset of your scroll view when the users changes it.So the basic functionality is done and it works, but it's not pretty.
The selected item didn't end centered in my selection image, which is just visually ugly. But you can fix it easily enough. You know the height of the items in the list and you know which item is selected, so programmatically scroll the wheel to have that item centered.
The other issue I had was momentum. Like a real wheel I wanted my picker to have momentum so if you gave it a hard flick it would go for a while, but if you gave it a gentle flick it would stop pretty fast. I had long list and if people were going from 7 to 70 I wanted them to be able to do it easily. If you are interested in in that, I can show you how I did it and post some code when I get back to the machine with my code on it.