iOS UIPickerView使用技巧

weixin_33912445發表於2018-09-14

修改字型大小及顏色

  • 方法一
- (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分割線顏色

相關文章