How can I change the font size and font style of UISearchBar in iOS 7?
UITextField *textField = [[searchBar subviews] objectAtIndex:1];
[textField setFont:[U
For those looking for a working Swift version, I've adapted this answer. Swift doesn't currently support Objc varargs methods, so it doesn't work directly with the above methods. We can work around this by making an objective-c category that doesn't use varargs and calls what we need:
// UIAppearance+Swift.h
@interface UIView (UIViewAppearance_Swift)
// appearanceWhenContainedIn: is not available in Swift. This fixes that.
+ (instancetype)my_appearanceWhenContainedIn:(Class<UIAppearanceContainer>)containerClass;
@end
—
// UIAppearance+Swift.m
@implementation UIView (UIViewAppearance_Swift)
+ (instancetype)my_appearanceWhenContainedIn:(Class<UIAppearanceContainer>)containerClass {
return [self appearanceWhenContainedIn:containerClass, nil];
}
@end
Just be sure to #import "UIAppearance+Swift.h"
in your bridging header.
Then just call:
UITextField.my_appearanceWhenContainedIn(UISearchBar.self).font = UIFont.systemFontOfSize(14.0)
As rmaddy said, you should not rely on the private subview structure of a standard UI component. That stuff changes and makes your code break. You should use provided APIs to do this stuff.
I think much safe approach is :
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont systemFontOfSize:14]];
or you can also use this sample code :
for(UIView *subView in searchBar.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
UITextField *searchField = (UITextField *)subView;
searchField.font = [UIFont systemFontOfSize:14];
}
}
The above code is also safer (at least compared to the one mentioned in the Question) as it's not using the index of subviews
.
Try this, It's Working Fine for iOS 5.0 and up: (iOS 7 also)
- (void)viewDidLoad
{
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"Helvetica" size:20]];
}
For iOS 8
- (void)viewDidLoad
{
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{
NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:20],
}];
}
The accepted answer did not work for me on iOS 7.1. I had to change it to this:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{
NSFontAttributeName: [UIFont fontWithName:@"Avenir-Heavy" size:20.],
}];
In Swift 5
code of @Piotr Tomasik still working in swift 5 after bit changes
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.font:UIFont(name: "poppins", size: 13)!]
For Swift 4 you need to reference the NSAttributedStringKey
enum:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
.defaultTextAttributes = [NSAttributedStringKey.font.rawValue: UIFont(...)]