Search code examples
iosobjective-cuitextfielduiappearance

Appearance Proxy overridden when resetting text


I am setting up my UI by using the UIAppearance Proxy. I setup my UITextfields to have a custom font like so:

[[UILabel appearanceWhenContainedIn:[RDTextField class], nil] setTextColor:[UIColor rds_purple]];
[[UILabel appearanceWhenContainedIn:[RDTextField class], nil] setFont:[UIFont rds_ralewayWithSize:20.0]];

This works perfectly, and when my textfields appear on screen they have the right font. However I enable my user to shuffle the strings that are in the textfields like this:

- (IBAction)shuffleValuesButtonPressed:(id)sender {
    self.randomStringTextfield.text = [self randomString];
}

When this happens the font goes from being my custom font to being the default black font. Why is this happening, and what is the solution to get my new string to be in my custom font that I setup in the appearance proxy?


Solution

  • According to the Apple developer docs:

    iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.

    So this solution works by removing everything and adding it back, but there is probably a better way:

    - (IBAction)shuffleValuesButtonPressed:(id)sender {
        self.randomStringTextfield.text = [self randomString];
        [self refreshViews];
    }
    
    - (void)refreshViews {
        for (UIWindow *window in [UIApplication sharedApplication].windows) {
            for (UIView *view in window.subviews) {
                [view removeFromSuperview];
                [window addSubview:view];
            }
        }
    }