系统原生的UISearchBar在iOS 11经历了一次变革,高度由原来的44变成了56 (使用默认高度的估计都被坑了),样式也发生了些微的变化,比如在未输入状态下圆角变化,放大镜图标和文本的文字不再居中而是靠左了。具体看图

一些主流App也常见在导航栏嵌入searchBar,以网易云音乐和知乎为例,左边是主页,右边是搜索页面 (注意光标)。

实现思路与案例

核心思想是设置导航栏的titleView和左右的barButtonItem。主要有3种方式

  1.  首页导航栏的titleView使用button来实现,搜索页面使用searchBar。
  2. 首页和搜索页面导航栏的titleView都是用searchBar,searchBar的样式针对两个页面做不同的修改。这种方式可以重用我们定制的searchBar,减少冗余。
  3. 首页导航栏titleView使用button来实现,搜索页面的使用textField。这种方式更彻底,更灵活,相对也更复杂一些。

为什么上面的titleView说是button不是其他的?其他的当然也可以实现。button自带imageView和titleLabel,只需要设置偏移量更容易达到我们想要的,而且视图层级更少,在流畅性方面更有保证些。

案例

网易云音乐首页和搜索页面的导航栏视图层级,titleView都使用MCSearchBar来实现,并且设置了导航栏左右两边的按钮 。这类似上文所说的第二种思路。

 

图中可以清楚看到知乎首页导航栏由2个button组成,搜索页面使用了textField,这类似上文提到的第三种思路。

实战

通过自定义SearchBar实现一个如下样式的导航栏

先自定义一个UISearchBar的初始化方法,观察一下首页和搜索页的异同,像searchField的大小背景色是一致的,可以这部分可以直接给定,而placeholder是不一样的,所以应该在调用的时候提供。以此类推,新建一个OHSearchBar类,一个初始化方法

- (instancetype)initWithFrame:(CGRect)frame placeholder:(NSString *)placeholder textFieldLeftView:(UIImageView *)leftView showCancelButton:(BOOL)showCancelButton tintColor:(UIColor *)tintColor { 
 if (self = [super initWithFrame:frame]) {
  self.frame = frame;
  self.tintColor = tintColor; //光标颜色
  self.barTintColor = [UIColor whiteColor];
  self.placeholder = placeholder;
  self.showsCancelButton = showCancelButton;
  self.leftView = leftView; // 用来代替左边的放大镜
  [self setImage:[UIImage imageNamed:@"clear"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal]; // 替换输入过程中右侧的clearIcon
 }
 return self;
}

新建一个首页OHHomeViewController,设置导航栏的titleView和rightBarButton

// navigation buttom
 UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeSystem];
 [messageButton setImage:[UIImage imageNamed:@"msg"] forState:UIControlStateNormal];
 messageButton.bounds = CGRectMake(0, 0, 30, 30);
 UIBarButtonItem *messageBarButton = [[UIBarButtonItem alloc] initWithCustomView:messageButton];
 self.navigationItem.rightBarButtonItem = messageBarButton;
 
 // search bar
 UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan"]];
 leftView.bounds = CGRectMake(0, 0, 24, 24);
 self.ohSearchBar = [[OHSearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)
            placeholder:@"点击我跳转"
          textFieldLeftView:leftView
           showCancelButton:NO
            tintColor:[UIColor clearColor]];
 self.navigationItem.titleView = self.ohSearchBar;

让我们来看下效果,左边为iOS 9,右边iOS 11

这时候可以看到几处差异

  1. searchBar的高度
  2. searchBar的textField的放大镜和文字位置
  3. textField的圆角不一致
  4. 更细心的还会发现,textField的位置不一致

解决方法: 第一和第二个问题,判断设备是否是iOS 11,若是则设置其高度,不是则让其placeholder居左。关键代码如下

if ([[UIDevice currentDevice] systemVersion].doubleValue >= 11.0) {
  [[self.heightAnchor constraintEqualToConstant:44.0] setActive:YES];
 } else {
  [self setLeftPlaceholder];
 }
- (void)setLeftPlaceholder {
 SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);
 if ([self respondsToSelector:centerSelector]) {
  BOOL centeredPlaceholder = NO;
  NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
  NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  [invocation setTarget:self];
  [invocation setSelector:centerSelector];
  [invocation setArgument:&centeredPlaceholder atIndex:2];
  [invocation invoke];
 }
}

对于第三和第四个问题,用KVC获取textField,并对其进行定制。令textField位置、大小、圆角一致。

- (void)layoutSubviews{
 [super layoutSubviews];
 // search field
 UITextField *searchField = [self valueForKey:@"searchField"];
 searchField.backgroundColor = DARK_BLUE_COLOR;
 searchField.textColor = [UIColor whiteColor];
 searchField.font = [UIFont systemFontOfSize:16];
 searchField.leftView = self.leftView;
 searchField.frame = CGRectMake(0, 8, SCREEN_WIDTH, 28);
 searchField.layer.cornerRadius = 5;
 searchField.layer.masksToBounds = YES;
 [searchField setValue:[UIColor whiteColor] forKeyPath:@"placeholderLabel.textColor"];
 [self setValue:searchField forKey:@"searchField"]; 
 self.searchTextPositionAdjustment = (UIOffset){10, 0}; // 光标偏移量
}

同样的,先看下运行效果

原本以为这下是没什么问题的,结果简直是坑

textFild的长度、位置、圆角都不一样 解释下这里出现的问题

观察上方图片上方的searchBar,会发现textField左边是圆角,右边是直角,说明是被截取的。导航栏titleView的范围就划分到了那个部分,而下边的searchBar连rightBarButton都不放过,直接抢占了位置。推测这是由于iOS 11导航栏视图层级变化产生的,可以这里了解下 www.jianshu.com/p/352f101d6… ,或者自行科普,不详细展开。所以对于searchBar的size设置要小心了,尽量控制在合适的范围。

textField的圆角是不一致的,自定义圆角大小时,取消其本身的圆角样式

searchField.borderStyle = UITextBorderStyleNone;

查看视图层级会发现,iOS 11以下,设置titleView,x的默认坐标居然是12,而iOS 11是0。所以设置textField的x坐标的话,在iOS 11下必须多出12才会是一致的位置。

 

修改代码上面的代码

- (void)layoutSubviews{
 [super layoutSubviews];
 // search field
 UITextField *searchField = [self valueForKey:@"searchField"];
 searchField.backgroundColor = DARK_BLUE_COLOR;
 searchField.textColor = [UIColor whiteColor];
 searchField.font = [UIFont systemFontOfSize:16];
 searchField.leftView = self.leftView;
 if (@available(iOS 11.0, *)) {
  // 查看视图层级,在iOS 11之前searchbar的x是12
  searchField.frame = CGRectMake(12, 8, SCREEN_WIDTH*0.8, 28);

 } else {
  searchField.frame = CGRectMake(0, 8, SCREEN_WIDTH*0.8, 28);
 }
 searchField.borderStyle = UITextBorderStyleNone;
 searchField.layer.cornerRadius = 5;
 searchField.layer.masksToBounds = YES;
 [searchField setValue:[UIColor whiteColor] forKeyPath:@"placeholderLabel.textColor"];
 [self setValue:searchField forKey:@"searchField"];
  self.searchTextPositionAdjustment = (UIOffset){10, 0}; // 光标偏移量
}

这时候就是我们想要的结果了。

首页暂时告一段落,接着开始我们的搜索页面。与首页不同的是需要searchBar与searchController配合使用。新建一个OHSearchController类 添加一个属性

@property (nonatomic, strong) OHSearchBar *ohSearchBar;

初始化代码

- (instancetype)initWithSearchResultsController:(UIViewController *)searchResultsController searchBarFrame:(CGRect)searchBarFrame placeholder:(NSString *)placeholder textFieldLeftView:(UIImageView *)leftView showCancelButton:(BOOL)showCancelButton barTintColor:(UIColor *)barTintColor{
 if (self = [super initWithSearchResultsController:searchResultsController]) {
  self.ohSearchBar = [[OHSearchBar alloc] initWithFrame:searchBarFrame
             placeholder:placeholder
           textFieldLeftView:leftView
            showCancelButton:YES
             tintColor:barTintColor];
  
  UIButton *button = [self.ohSearchBar valueForKey:@"cancelButton"];
  button.tintColor = [UIColor whiteColor];
  [button setTitle:@"取消" forState:UIControlStateNormal];
  [self.ohSearchBar setValue:button forKey:@"cancelButton"];
 }
 return self;
}

接着是我们的视图控制器OHSearchViewController

UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
 leftView.bounds = CGRectMake(0, 0, 24, 24);
 self.ohSearchController = [[OHSearchController alloc] initWithSearchResultsController:self
                   searchBarFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)
                    placeholder:@"请输入搜索内容进行搜索"
                  textFieldLeftView:leftView
                   showCancelButton:YES
                    barTintColor:BASE_BLUE_COLOR];
 
 [self.ohSearchController.ohSearchBar becomeFirstResponder];
 self.ohSearchController.ohSearchBar.delegate = self;
 [self.ohSearchController.ohSearchBar setLeftPlaceholder];
 self.navigationItem.titleView = self.ohSearchController.ohSearchBar;
 self.navigationItem.hidesBackButton = YES;

完成这一步后到了交互环节了,点击首页的searchBar跳转搜索页面,点击搜索页面的取消按钮返回到首页。 首页设置searchbar的代理,并完成一下代理方法

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
 OHSearchViewController *ohSearchViewController = [[OHSearchViewController alloc] init];
 [self.navigationController pushViewController:ohSearchViewController animated:NO];
 return YES;
}

搜索页设置searchbar的代理,并完成一下代理方法

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
 [self.navigationController popViewControllerAnimated:NO];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
 [self.ohSearchController.ohSearchBar resignFirstResponder];
 // 让取消按钮一直处于激活状态
 UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"];
 cancelBtn.enabled = YES;
}

这时候问题又出现了,点击搜索页面的取消按钮,没有跳回首页而是还在这个页面。但是可以看到屏幕的闪动。通过打印消息发现,点了取消按钮,执行了首页的- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar方法。 仔细推敲之后想明白了原因是没有取消第一响应者,加上导航栏的交互机制,pop到上个页面的时候并不会进行页面刷新导致了这个问题。 解决办法在首页要push搜索页面的时候取消第一响应者

- (void)viewWillDisappear:(BOOL)animated {
 [self.ohSearchBar resignFirstResponder];
}

到此,便大功告成了。可以看下源码加深理解。希望对大家的学习有所帮助,也希望大家多多支持Devmax。

iOS定制UISearchBar导航栏同步iOS11的方法的更多相关文章

  1. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  2. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  4. ios – Testflight无法安装应用程序

    我有几个测试人员注册了testflight并连接了他们的设备……他们有不同的ios型号……但是所有这些都有同样的问题.当他们从“safari”或“testflight”应用程序本身单击应用程序的安装按钮时……达到约90%并出现错误消息…

  5. ibm-mobilefirst – 在iOS 7.1上获取“无法安装应用程序,因为证书无效”错误

    当我的客户端将他们的设备更新到iOS7.1,然后尝试从AppCenter更新我们的应用程序时,我收到了上述错误.经过一番搜索,我找到了一个类似问题的帖子here.但是后来因为我在客户端使用AppCenter更新应用程序的环境中,我无法使用USB插件并为他们安装应用程序.在发布支持之前,是否有通过AppCenter进行下载的解决方法?

  6. ios – 视图的简单拖放?

    我正在学习iOS,但我找不到如何向UIView添加拖放行为.我试过了:它说“UIView没有可见的接口声明选择器addTarget”此外,我尝试添加平移手势识别器,但不确定这是否是我需要的它被称为,但不知道如何获得事件的坐标.在iOS中注册移动事件回调/拖放操作的标准简单方法是什么?

  7. ios – 什么控制iTunes中iPhone应用程序支持的语言列表?

    什么控制iPhone应用程序的iTunes页面中支持的语言?

  8. ios – 获得APNs响应BadDeviceToken或Unregistered的可能原因是什么?

    我知道设备令牌在某些时候是有效的.用户如何使其设备令牌变坏?从关于“未注册”的文档:Thedevicetokenisinactiveforthespecifiedtopic.这是否意味着应用程序已被删除?.您应该看到四种分发方法:如果您选择AppStore或Enterprise,您将在后面的对话框中看到Xcode将APNS权利更改为生产:如果选择AdHoc或Development,则aps-environment下的文本将是开发,然后应与后端的配置匹配.

  9. ios – 当我关闭应用程序时,我从调试器获得消息:由于信号15而终止

    我怎么能解决这个问题,我不知道这个链接MypreviousproblemaboutCoredata对我的问题有影响吗?当我cmd应用程序的Q时,将出现此消息.Messagefromdebugger:Terminatedduetosignal15如果谁知道我以前的问题的解决方案,请告诉我.解决方法>来自调试器的消息:每当用户通过CMD-Q(退出)或STOP手动终止应用程序(无论是在iOS模拟器中还是

  10. ios – NSUbiquityIdentityDidChangeNotification和SIGKILL

    当应用程序被发送到后台时,我们会删除观察者吗?我遇到的问题是,当UbiquityToken发生变化时,应用程序终止,因为用户已经更改了iCloud设置.你们如何设法订阅这个通知,如果你不这样做,你会做什么来跟踪当前登录的iCloud用户?

随机推荐

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. iOS – genstrings:无法连接到输出目录en.lproj

    使用我桌面上的项目文件夹,我启动终端输入:cd然后将我的项目文件夹拖到终端,它给了我路径.然后我将这行代码粘贴到终端中找.-name*.m|xargsgenstrings-oen.lproj我在终端中收到此错误消息:genstrings:无法连接到输出目录en.lproj它多次打印这行,然后说我的项目是一个目录的路径?没有.strings文件.对我做错了什么的想法?

  3. iOS 7 UIButtonBarItem图像没有色调

    如何确保按钮图标采用全局色调?解决方法只是想将其转换为根注释,以便为“回答”复选标记提供更好的上下文,并提供更好的格式.我能想出这个!

  4. ios – 在自定义相机层的AVFoundation中自动对焦和自动曝光

    为AVFoundation定制图层相机创建精确的自动对焦和曝光的最佳方法是什么?

  5. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  6. ios – 在没有iPhone6s或更新的情况下测试ARKit

    我在决定下载Xcode9之前.我想玩新的框架–ARKit.我知道要用ARKit运行app我需要一个带有A9芯片或更新版本的设备.不幸的是我有一个较旧的.我的问题是已经下载了新Xcode的人.在我的情况下有可能运行ARKit应用程序吗?那个或其他任何模拟器?任何想法或我将不得不购买新设备?解决方法任何iOS11设备都可以使用ARKit,但是具有高质量AR体验的全球跟踪功能需要使用A9或更高版本处理器的设备.使用iOS11测试版更新您的设备是必要的.

  7. 将iOS应用移植到Android

    我们制作了一个具有2000个目标c类的退出大型iOS应用程序.我想知道有一个最佳实践指南将其移植到Android?此外,由于我们的应用程序大量使用UINavigation和UIView控制器,我想知道在Android上有类似的模型和实现.谢谢到目前为止,guenter解决方法老实说,我认为你正在计划的只是制作难以维护的糟糕代码.我意识到这听起来像很多工作,但从长远来看它会更容易,我只是将应用程序的概念“移植”到android并从头开始编写.

  8. ios – 在Swift中覆盖Objective C类方法

    我是Swift的初学者,我正在尝试在Swift项目中使用JSONModel.我想从JSONModel覆盖方法keyMapper,但我没有找到如何覆盖模型类中的Objective-C类方法.该方法的签名是:我怎样才能做到这一点?解决方法您可以像覆盖实例方法一样执行此操作,但使用class关键字除外:

  9. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  10. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

返回
顶部