我正在尝试获得一个UIPicker
显示所选行的绿色文本。我使用该pickerView:viewForRow:forComponent:reusingView:
方法为它创建一个 UILabel:
- (UIView*) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *label = (UILabel*)view;
if (label == nil) {
label = [UILabel new];
label.font = [UIFont boldSystemFontOfSize: 24];
label.adjustsFontSizeToFitWidth = YES;
}
UIColor *color = (row == [pickerView selectedRowInComponent: component]) ? RGBx(0x579B2F) : UIColor.whiteColor;
label.textAlignment = component == 0 ? NSTextAlignmentRight : NSTextAlignmentLeft;
NSMutableAttributedString *string;
if (component == 0) {
string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%3lu.", row]];
[string addAttribute:NSForegroundColorAttributeName value: color range:NSMakeRange(0, string.length - 1)];
[string addAttribute:NSForegroundColorAttributeName value: [UIColor clearColor] range:NSMakeRange(string.length - 1,1)];
}
else {
string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@".%02lu", row % 60]];
[string addAttribute:NSForegroundColorAttributeName value: [UIColor clearColor] range:NSMakeRange(0,1)];
[string addAttribute:NSForegroundColorAttributeName value: color range:NSMakeRange(1,string.length - 1)];
}
label.attributedText = string;
return label;
}
里面还有一些额外的东西,让两个轮子紧密对齐,但有一点间距(透明周期)。它主要工作:
最初,它看起来很完美,绿色选择和白色/灰色其他选择。问题是当我滚动轮子时,它们并不总是以绿色结束。有时他们会这样做,但并非总是如此。可以看出,有时滚动的值即使不再被选中也会保持绿色(见09
右上角)。
我该怎么做才能只保持绿色并始终在选定的行上?