Jaehyun Jeon
Jaehyun Jeon

Reputation: 21

ios appearanceWhenContainedIn only works once

In viewDidLoad, I create a searchBar, set it as the titleView inside the navigationBar, and call appearanceWhenContainedIn for the font size of the text inside the searchBar. When the view loads for the first time, the appearanceWhenContainedIn works fine, but when the viewController is dismissed then pushed again, the appearanceWhenContainedIn method doesn't work although it is called. The same code inside viewDidLoad is processed, yet has different results. How can this possibly happen?

override func viewDidLoad() {
    super.viewDidLoad()

    var searchBar:UISearchBar = UISearchBar()
    searchBar.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 20)
    searchBar.autocapitalizationType = UITextAutocapitalizationType.None
    searchBar.delegate = self
    searchBar.searchBarStyle = UISearchBarStyle.Minimal
    searchBar.sizeToFit()
    searchBar.tintColor = UIColor.whiteColor()
    searchBar.placeholder = "username"
    searchBar.barTintColor = UIColor.whiteColor()
    searchBar.backgroundColor = UIColor.clearColor()
    self.navigationItem.titleView = searchBar
    AppearanceBridge.setAppearance()
}

The code is in Swift, and I couldn't find appearanceWhenContainedIn for Swift, so I call an Objective-C method in a dummy class. (AppearanceBridge.setAppearance())

@import UIKit;
#import "AppearanceBridge.h"

@implementation AppearanceBridge
+ (void)setAppearance {
    [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont systemFontOfSize:17]];
    [[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setFont: [UIFont systemFontOfSize:17]];
    [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]];
}
@end

I'm including both the .h and .m files because I am not experienced with Objective-C and there may be something wrong with the code.

#import <Foundation/Foundation.h>

@interface AppearanceBridge : NSObject
+ (void)setAppearance;
@end

Thanks!

Upvotes: 2

Views: 519

Answers (1)

dkornev
dkornev

Reputation: 11

I had the same problem and I founded a workaround which worked for me. You should get and style UITextField/UILabel from the UISearchBar Subviews manually each time you create it. It's better to create a separate method I guess. I'm using C# and for me it looks like that:

public static void StyleSearchBar(UISearchBar searchBar)
{
   var container = searchBar.Subviews[0];
   var textField = container.FirstOrDefault(x => x is UITextField);
   textField.BackgroundColor = UIColor.Red;
}

I know that it's not a ObjC or Swift answer, but I'm sure that it's easy to get the idea.

Upvotes: 1

Related Questions