更改UIDatePicker字体颜色?

46

我想做的只是改变UIDatePicker的字体颜色。我研究了其他问题,但它们都涉及到更改其他属性和自定义整个外观。我只想把字体颜色从黑色改成白色。我觉得很难相信我不能完成这样一个看似简单的任务。为什么tint color不起作用呢?它甚至有用吗?


在上面的问题中,我找到了我的解决方案。 - MarMass
17个回答

2
[date_picker setValue:textColor forKey:@"textColor"];
[date_picker performSelector:@selector(setHighlightsToday:) withObject:NO];

2

这个UIDatePicker的子类适用于iOS 7。它不太美观,但能够完成工作。

#define kNotification_UIView_didAddSubview @"kNotification_UIView_didAddSubview"
@implementation UIView (addSubview)

-(void) didAddSubview:(UIView *)subview{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_UIView_didAddSubview object:self];
}
@end


@interface DatePicker ()
@property (nonatomic, strong) UIColor* textColor;
@end

@implementation DatePicker

-(id) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        [self setup];
    }
    return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self){
        [self setup];
    }
    return self;
}

-(void) setup{
    self.textColor = [UIColor darkTextColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subviewsUpdated:) name:kNotification_UIView_didAddSubview object:nil];
}

-(void) dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) updateLabels:(UIView*) view{
    for (UILabel* label in view.subviews){
        if ([label isKindOfClass:[UILabel class]]){
            label.textColor = self.textColor;
        }else{
            [self updateLabels:label];
        }
    }
}

-(BOOL) isSubview:(UIView*) view{
    if (view == nil){
        return NO;
    }
    if (view.superview == self){
        return YES;
    }
    return [self isSubview:view.superview];
}

-(void) subviewsUpdated:(NSNotification*) notification{
    if ([notification.object isKindOfClass:NSClassFromString(@"UIPickerTableView")] && [self isSubview:notification.object]){
        [self updateLabels:notification.object];
    }
}

@end

2
在Storyboard中添加名为"textColor"的运行时属性,如下图所示。

enter image description here


1
作为对@Jeremiah答案的替代方案,您可以使用以下内容:
datePicker.setValue(UIColor.redColor(), forKey: "textColor")
datePicker.sendAction("setHighlightsToday:", to: nil, forEvent: nil)
datePicker.setDate(NSDate(timeIntervalSinceReferenceDate: 0), animated: false)

它将删除Today(您将看到当前日期),但它将具有正确的颜色。


1
直到将textColor设置在layoutSubviews()内部,它才起作用。
override func layoutSubviews() {
    super.layoutSubviews()
    datePicker.backgroundColor = .black
    datePicker.setValue(.white, forKeyPath: "textColor")
}

0
[my_date_picker setValue:[UIColor whiteColor] forKey:@"textColor"];

看起来在iOS 13或更高版本上似乎无法正常工作,您可以为UIDatePicker设置overrideUserInterfaceStyle属性以确定它显示白色还是黑色。


0

只需使用 datePicker.tintColor = .red 或任何您想要的颜色即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接