ios appearanceWhenContainedIn只工作一次

时间:2015-02-27 03:09:27

标签: ios objective-c swift uisearchbar uiappearance

在viewDidLoad中,我创建了一个searchBar,将其设置为navigationBar中的titleView,并调用appearanceWhenContainedIn作为searchBar内文本的字体大小。当视图第一次加载时,appearanceWhenContainedIn工作正常,但是当viewController被解除然后再次推送时,appearanceWhenContainedIn方法虽然被调用但不起作用。处理viewDidLoad中的相同代码,但结果不同。怎么可能发生这种情况?

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()
}

代码在Swift中,我无法在Swift中找到outlookContainedIn,所以我在一个虚拟类中调用了Objective-C方法。 (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

我包括.h和.m文件,因为我没有使用Objective-C,但代码可能有问题。

#import <Foundation/Foundation.h>

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

谢谢!

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,我找到了一个适合我的解决方法。每次创建时,都应手动从UISearchBar子视图中获取UITextField / UILabel样式。我猜最好创建一个单独的方法。我正在使用C#,对我来说它看起来像是:

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

我知道这不是ObjC或Swift的答案,但我确信这很容易理解。