UiPickerView with custom fixed label and autolayout
cocoa, uipickerview
Solution
I faced a similar problem in an App I worked on and decided on the following:
i. Create the UIPicker
ii. Find the midpoint of the presented Picker rows.
iii. Add two UILabels to the screen and in - `(void)layoutSubview;` make sure the labels are always position next to the midpoints.
I only needed portrait mode support in my project, but should work fine for landscape as well. Just choose a wide enough, row width, such that you do not have any overlap with the data inside the picker. Here a snippet of code for the UIPicker:
#pragma mark - Picker View
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if(component == 0) {
return self.hourPickerData.count;
} else {
return self.minutePickerData.count;
}
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
return 40;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 30;
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
NSString *text;
if(component == 0) {
text = self.hourPickerData[row];
} else {
text = self.minutePickerData[row];
}
UILabel *label = (UILabel*)view;
if(view == nil) {
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
label.backgroundColor = [UIColor clearColor];
label.text = text;
label.textAlignment = NSTextAlignmentCenter;
label.textColor = LYTiT_HEADER_COLOR;
label.font = [UIFont fontWithName:LT_HELVETICA size:16];
}
return label;
}
Problem
I need to implement a `UIPickerView` to choose hours, minutes and seconds. I need to have a label, next to each component that stay fixed when the picker spin. For example you can look at the timer section of the Apple Clock app. I put an image for reference of course I need a picker with 3 components but the problem is the same. I found a lot of solution to add a label as a subview and position it using some frames and manual adjustment but a can' t make it work with AutoLayout and i don' t find a solution on the web. Anyone has solved this problem? thanks