所有,
我想将UISearchBar添加到UINavigationbar,我不想以编程方式使用UISearchController,Just UISearchbar,它也必须在横向上工作。
我试过它在Portrait中运行良好,但在Landscape中,我在iPhone X宽度方面存在问题。我们可以使用约束吗?
下面是代码
CGFloat width = [UIScreen mainScreen].bounds.size.width;
search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, width - 2 * 44 - 2 * 15, 44)];
search.delegate = self; // search.tintColor = [UIColor redColor];
search.searchBarStyle = UISearchBarStyleMinimal;
search.placeholder = @"Search";
search.translucent = NO;
search.opaque = NO;
search.showsCancelButton = NO;
[search setBackgroundImage:[[UIImage alloc] init]];
//customize textfield inside UISearchBar
@try {
for (id object in [[[search subviews] firstObject] subviews])
{
if (object && [object isKindOfClass:[UITextField class]])
{
UITextField *textFieldObject = (UITextField *)object;
textFieldObject.backgroundColor = [UIColor whiteColor];
textFieldObject.borderStyle = UITextBorderStyleRoundedRect;
textFieldObject.layer.borderColor = (__bridge CGColorRef _Nullable)([brandingObj getValueForKey:navBarTitleColor]);
textFieldObject.layer.borderWidth = 1.0;
break;
}
}
}
@catch (NSException *exception) {
NSLog(@"Error while customizing UISearchBar");
}
@finally {
}
我不明白你为什么要使用UISearchDisplayController,它的高度可配置和苹果推荐,使用几何(CGRecr,CGFrame等)调整UIKit对象布局可能很痛苦,使用自动布局避免UIKits便利初始化器,到调整后来的约束。
无论如何,如果你想用这种方式明确地做,这应该工作。
#import "ViewController.h"
@interface ViewController ()<UISearchBarDelegate>
@property UISearchBar *searchbar;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_searchbar = [UISearchBar new];
_searchbar.delegate = self;
_searchbar.searchBarStyle = UISearchBarStyleMinimal;
self.navigationItem.titleView = self.searchbar;
// Do any additional setup after loading the view, typically from a nib.
}
也许你应该需要配置外观,看看here
干杯。