简体   繁体   English

更改 UIDatePicker 字体颜色?

[英]Change UIDatePicker font color?

All I want to do is change the font color of the UIDatePicker.我想要做的就是更改 UIDatePicker 的字体颜色。 I've researched other questions but they're all involving changing other properties and customizing the entire look.我研究了其他问题,但它们都涉及更改其他属性和自定义整个外观。 All I want to do is just change the font color from black to white.我想要做的只是将字体颜色从黑色更改为白色。 I find it hard to believe that I can't do such a seemingly simple task.我很难相信我做不到这么简单的任务。 And why wouldn't the tint color affect it?为什么色调颜色不会影响它? Does it even do anything?它甚至做任何事情吗?

All I need (on iOS 8.x and 9.0) is this one line to change the font color:我只需要(在 iOS 8.x 和 9.0 上)这一行来更改字体颜色:

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

No subclassing or invoking of private APIs...没有子类化或调用私有 API...


Note: today's current date will still be highlighted (in newer iOS versions).注意:今天的当前日期仍将突出显示(在较新的 iOS 版本中)。 You can get around this by using the following code:您可以使用以下代码解决此问题:

if ([my_date_picker respondsToSelector:sel_registerName("setHighlightsToday:")]) {

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"

        [my_date_picker performSelector:@selector(setHighlightsToday:) withObject:[NSNumber numberWithBool:NO]];

#pragma clang diagnostic pop

}

As of Swift 2.1:从 Swift 2.1 开始:

picker.setValue(UIColor.whiteColor(), forKey: "textColor")
picker.sendAction("setHighlightsToday:", to: nil, forEvent: nil)
let date = NSDate()
picker.setDate(date, animated: false)

Instead of "today" you will see the current day,而不是“今天”,你会看到今天,

One other alternative to @Jeremiah answer is to define those values in Interface Builder. @Jeremiah 答案的另一种替代方法是在 Interface Builder 中定义这些值。 I prefer this one because there is no code to add in your ViewController.我更喜欢这个,因为没有代码可以添加到您的 ViewController 中。

Click into your DatePicker view and customise it from the Attribute inspector as in the screenshot.单击您的 DatePicker 视图并从属性检查器自定义它,如屏幕截图所示。截图

Works for Swift 2, 3, 4 and probably for Swift < 2. (not tested)适用于 Swift 2、3、4,可能适用于 Swift < 2。(未测试)

Next solution comes from "arturgrigor" and it works great in my apps, just copy it, paste it in viewDidLoad method, and enjoy it :下一个解决方案来自“arturgrigor”,它在我的应用程序中运行良好,只需复制它,将其粘贴到 viewDidLoad 方法中,然后享受它:

[my_datePicker setValue:[UIColor whiteColor] forKeyPath:@"textColor"];
SEL selector = NSSelectorFromString( @"setHighlightsToday:" );
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature :
                           [UIDatePicker 
                            instanceMethodSignatureForSelector:selector]];
BOOL no = NO;
[invocation setSelector:selector];
[invocation setArgument:&no atIndex:2];
[invocation invokeWithTarget:my_datePicker];

According to Apple's UIKit User Interface Catalog , developers are not allowed to customize date pickers.根据Apple's UIKit User Interface Catalog ,不允许开发人员自定义日期选择器。

I've seen other StackOverflow answers for similar questions that suggest making a fake UIDatePicker using UIPickerView and customizing that .我已经看到其他类似问题的 StackOverflow 答案,这些答案建议使用 UIPickerView 制作一个假的 UIDatePicker 并自定义它

I also found an open source date picker on GitHub (at https://github.com/mwermuth/MWDatePicker ) that might help a bit.我还在 GitHub 上找到了一个开源日期选择器(位于 https://github.com/mwermuth/MWDatePicker ) ,它可能会有所帮助。 It allows for different background and selector styles, but not a different font or font attributes.... yet.它允许不同的背景和选择器样式,但不允许不同的字体或字体属性......

To change UIDatePicker text color use:要更改 UIDatePicker 文本颜色,请使用:

    // MARK: - Helping content 

    private enum DatePickerProperties: String {
        case TextColor = "textColor"
        case HighlightsToday = "highlightsToday"
    }

    // MARK: - Outlets

    @IBOutlet private weak var datePicker: UIDatePicker!

    // MARK: - Lifecicle

    public override func awakeFromNib() {
        super.awakeFromNib()

        self.datePicker.setValue(UIColor.whiteColor(), forKey: DatePickerProperties.TextColor.rawValue)
        self.datePicker.setValue(false, forKey: DatePickerProperties.HighlightsToday.rawValue)
    }

It works like a charm with xCode 7.3 and Swift 2.3.它在 xCode 7.3 和 Swift 2.3 中就像一个魅力。

If anyone wants the swift solution, I placed the following in viewDidLoad:如果有人想要快速解决方案,我在 viewDidLoad 中放置了以下内容:

    birthdayDatePicker.setValue(DesignHelper.getOffWhiteColor(), forKey: "textColor")
    birthdayDatePicker.performSelector("setHighlightsToday:", withObject:DesignHelper.getOffWhiteColor())

For Xamarin developers:对于 Xamarin 开发人员:

DatePicker.SetValueForKey(UIColor.White, new NSString("textColor"));
DatePicker.SetValueForKey(FromObject(false), new NSString("highlightsToday"));

It´s working like a charm.它就像一个魅力。 Tested in iOS 9 and 10在 iOS 9 和 10 中测试

You can also add this as an IBDesignable if you want to configure this within InterFace Builder.如果您想在 InterFace Builder 中配置它,您也可以将其添加为 IBDesignable。

    import UIKit

@IBDesignable
extension UIDatePicker {
    @IBInspectable var textLabelColor: UIColor? {
        get {
            return self.valueForKey("textColor") as? UIColor
        }
        set {
            self.setValue(newValue, forKey: "textColor")
            self.performSelector("setHighlightsToday:", withObject:newValue) //For some reason this line makes the highlighted text appear the same color but can not be changed from textColor. 
        }
    }
}

I stumbled upon a surprisingly clean solution using UIAppearance , without using any KVC, swizzling, or otherwise private API.我偶然发现了一个使用UIAppearance的非常干净的解决方案,没有使用任何 KVC、 UIAppearance或其他私有 API。 I found that attempting to set the textColor via UIAppearance for any UILabel within a UIDatePicker had no affect, but a custom appearance property that simply called the regular textColor setter worked just fine.我发现尝试通过UIAppearanceUIDatePicker任何UILabel设置textColor没有任何影响,但是简单地调用常规textColor setter 的自定义外观属性工作得很好。

// Implement a custom appearance property via a UILabel category
@interface UILabel (PickerLabelTextColor)

@property (nonatomic, strong) UIColor * textColorWorkaround UI_APPEARANCE_SELECTOR;

@end

@implementation UILabel (PickerLabelTextColor)

- (UIColor *)textColorWorkaround {
    return self.textColor;
}

- (void)setTextColorWorkaround:(UIColor *)textColor {
    self.textColor = textColor;
}

@end

And then use as follows:然后使用如下:

UILabel *pickerLabelProxy = [UILabel appearanceWhenContainedInInstancesOfClasses:@[UIDatePicker.class]];
pickerLabelProxy.textColorWorkaround = UIColor.lightGrayColor;

Swift Version迅捷版

UILabel extension: UILabel 扩展:

extension UILabel {
    @objc dynamic var textColorWorkaround: UIColor? {
        get {
            return textColor
        }
        set {
            textColor = newValue
        }
    }
}

Appearance proxy use:外观代理使用:

let pickerLabelProxy = UILabel.appearance(whenContainedInInstancesOf: [UIDatePicker.self])
pickerLabelProxy.textColorWorkaround = UIColor.lightGray

This subclass of UIDatePicker works for iOS 7. Its not pretty but gets the job done. 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
[date_picker setValue:textColor forKey:@"textColor"];
[date_picker performSelector:@selector(setHighlightsToday:) withObject:NO];

Add Runtime Attribute named "textColor" from Storyboard as shown in following image.从 Storyboard 添加名为“textColor”的运行时属性,如下图所示。

在此处输入图片说明

As alternative to @Jeremiah answer, you can use this:作为@Jeremiah 答案的替代方法,您可以使用以下方法:

datePicker.setValue(UIColor.redColor(), forKey: "textColor")
datePicker.sendAction("setHighlightsToday:", to: nil, forEvent: nil)
datePicker.setDate(NSDate(timeIntervalSinceReferenceDate: 0), animated: false)

it will remove Today (you will see current date), but it will be with right color.它将删除今天(您将看到当前日期),但它将具有正确的颜色。

Possible troubles: if you change color dynamically, I didn't find a way to reload date picker.可能的问题:如果你动态改变颜色,我没有找到重新加载日期选择器的方法。 So, the user will see previous color and only after scroll, color will changed to a new one.因此,用户将看到以前的颜色,只有在滚动后,颜色才会更改为新的颜色。 -> Solved, by last string. -> 已解决,通过最后一个字符串。 Looks like Voodoo, but it works...看起来像巫毒,但它有效......

This answer suitable for Swift 2.1这个答案适用于 Swift 2.1

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

It didn't work until textColor was set inside layoutSubviews()直到 textColor 在 layoutSubviews() 中设置后才起作用

override func layoutSubviews() {
    super.layoutSubviews()
    datePicker.backgroundColor = .black
    datePicker.setValue(.white, forKeyPath: "textColor")
}
[my_date_picker setValue:[UIColor whiteColor] forKey:@"textColor"];

它似乎不适用于 ios 13 或更高版本,您可以为 UIDatePicker 设置overrideUserInterfaceStyle属性以确定它显示白色或黑色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM