iOS UIPickerView使用技巧

2018-09-14  本文已影响328人  Wynter_Wang

修改字体大小及颜色

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSDictionary* titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                         [UIColor colorWithRed:12.f/255.f green:14.f/255.f blue:14.f/255.f alpha:1], NSForegroundColorAttributeName,
                                         [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold], NSFontAttributeName,
                                         nil];

    NSString *str = self.dataAry[row];
    NSAttributedString *restr = [[NSAttributedString alloc] initWithString:str attributes:titleTextAttributes];
    return restr;
}

注意:不能和titleForRow方法同时使用

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        pickerLabel.textColor = [UIColor colorWithRed:12.f/255.f green:14.f/255.f blue:14.f/255.f alpha:1];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];

    return pickerLabel;
}

修改分割线颜色

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        pickerLabel.textColor = [UIColor colorWithRed:12.f/255.f green:14.f/255.f blue:14.f/255.f alpha:1];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    [self changeSpearatorLineColor];
    return pickerLabel;
}

#pragma mark - 改变分割线的颜色
- (void)changeSpearatorLineColor {
    for(UIView *speartorView in _dataPickerView.subviews) {
        if (speartorView.frame.size.height < 1) {
            speartorView.backgroundColor = [UIColor redColor];
        }
    }
}

注意:这个方法只有放到下面的方法才有效果,获取pickerView:viewForRow:forComponent:reusingView:中定义的View,当pickerView:viewForRow:forComponent:reusingView:未实现或者行或分组不可用时返回nil

参考

iOS 改变UIPickerView分割线颜色

上一篇下一篇

猜你喜欢

热点阅读