查看完整文章请到源地址:http://386502324.blog.163.com/blog/static/113469377201510282124497/

一: 问题描述,为什么要去完全自定义searchBar
相 信许多同学在开发中,会遇到UISearchBar的自订制问题。比如一个简单的placeholder永远居左,且关键字会不断变化,就会逼疯很多人, 使用空格符达到效果。自从iOS7之后,如果不想使用自带的searchBar的默认效果就更容易遇到各种问题。因此,使用textField去完全解决 自定义的方法无疑是最有效率的。

二:思路,如何去自定义searchBar
作为苹果的封装类,searchBar无非是给大家便利的提供了一种使用textField的类。其核心还是textField。因此,我们的封装,也必须是围绕textField来完成的。
1:主体是一个view
2:放大镜图片,可以在主view上添加imageView,也可以使用textField的leftView;
3:取消按钮,完全可以不放到主view中,在外界使用的时候再去自行创建使用。
4:textField
5:重点:代理的实现,无非是将textField的代理无缝结合移植到封装类,可以参考系统的searchbar的代理,也写代理。
6:既然是自封装,属性完全可以多设置一些,方便大家调用。

三:代码示例
下面就是我花了半天时间简单封装的searchBar,虽然还会有些不太完善的地方,但是绝大部分功能都可以正常使用了。可以根据自己的需求,继续完善属性,添加方法,甚至代理方法。先是.h中。

//
//  OCSearchBar.h
//  OpenCourse
//
//  Created by 徐坤 on 15/11/27.
//
// 不让外界直接调用textField,用起来会更像系统的searchBar的API,完善属性后,会将textField拿到.m中

#import <UIKit/UIKit.h>

@class OCSearchBar;

@protocol OCSearchBarDelegate <NSObject>

@optional

- (BOOL)OCSearchBarShouldBeginEditing:(OCSearchBar *)searchBar;
- (void)OCSearchBarTextDidBeginEditing:(OCSearchBar *)searchBar;
- (BOOL)OCSearchBarShouldEndEditing:(OCSearchBar *)searchBar;
- (void)OCSearchBarTextDidEndEditing:(OCSearchBar *)searchBar;

- (void)OCSearchBar:(OCSearchBar *)searchBar textDidChange:(NSString *)searchText;
- (BOOL)OCSearchBar:(OCSearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- (void)OCSearchBarSearchButtonClicked:(OCSearchBar *)searchBar;

@end

@interface OCSearchBar : UIView <UITextFieldDelegate>

@property (nonatomic, strong) UIImage *backViewImage;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIImageView *leftImageView;//左侧放大镜
@property (nonatomic, copy  ) NSString *placeholder;
@property (nonatomic, strong) UIFont *font;
@property (nonatomic, copy)   NSString *text;
@property (nonatomic, strong) UIColor *placeholderColor;
@property (nonatomic, strong) UIColor *textColor;

@property (nonatomic, assign) BOOL isFirstResponder;

@property (nonatomic, weak) id <OCSearchBarDelegate>delegate;

- (instancetype)initWithFrame:(CGRect)frame;

- (void)resignFirstResponder;
- (void)becomeFirstResponder;

@end

============然后是实现文件.m=========自行粘贴到自己项目中即可。
//
//  OCSearchBar.m
//  OpenCourse
//
//  Created by 徐坤 on 15/11/27.
//
//

#import "OCSearchBar.h"

@interface OCSearchBar ()
@property (nonatomic, strong) UIImageView *backGroundView;

@end

@implementation OCSearchBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self setupSubviews];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)setupSubviews {
   
    self.backGroundView = [[UIImageView alloc] initWithFrame:self.bounds];
    [self addSubview:self.backGroundView];
   
    self.textField = [[UITextField alloc] initWithFrame:self.bounds];
    self.textField.backgroundColor = [UIColor clearColor];
    self.textField.delegate = self;
    self.textField.clearButtonMode = YES;
    self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textField.returnKeyType = UIReturnKeySearch;
    //self.textField.leftViewMode = UITextFieldViewModeAlways;
    [self addSubview:self.textField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OCSearchBarDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    [self setupDefaultLeftImageView];
    [self setupDefaultBackGroundView];
}

- (void)setupDefaultBackGroundView {
   
    // 使用颜色创建UIImage
    CGSize imageSize = self.bounds.size;
    UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);
    [RGB(26, 66, 38) set];
    UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    self.backGroundView.layer.cornerRadius = 6;
    self.backGroundView.layer.masksToBounds = YES;
   
    [self.backGroundView setImage:colorImage];
   
}

- (void)setupDefaultLeftImageView {
    UIImageView *leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search_fdj"]];
    [leftImageView setFrame:CGRectMake(13, 6, 18, 18)];
    self.leftImageView = leftImageView;
}

- (void)setFont:(UIFont *)font {
    self.textField.font = font;
   
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    [self.textField setValue:placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
   
}

- (void)setTextColor:(UIColor *)textColor {
    [self.textField setTextColor:textColor];
   
}

- (void)setText:(NSString *)text {
    self.textField.text = text;
}

- (NSString *)text {
    return self.textField.text;
}

- (void)setBackViewImage:(UIImage *)backViewImage {
    [self.backGroundView setImage:backViewImage];
   
}

- (void)setLeftImageView:(UIImageView *)leftImageView {
    if (self.leftImageView.superview) {
        [self.leftImageView removeFromSuperview];
    }
    [self addSubview:leftImageView];
    CGRect rect = self.textField.bounds;
    rect.origin.x = rect.origin.x+leftImageView.frame.origin.x+leftImageView.frame.size.width+5;
    rect.size.width = rect.size.width - leftImageView.frame.origin.x - leftImageView.frame.size.width-5;
    [self.textField setFrame:rect];
   
}

- (void)setPlaceholder:(NSString *)placeholder {
    self.textField.placeholder = placeholder;
}

- (void)resignFirstResponder {
    [self.textField resignFirstResponder];
}

- (void)becomeFirstResponder {
    [self.textField becomeFirstResponder];
}

#pragma mark -
#pragma mark - OCTextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBarShouldBeginEditing:)] ) {
        return [self.delegate OCSearchBarShouldBeginEditing:self];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.isFirstResponder = YES;
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBarTextDidBeginEditing:)]) {
        [self.delegate OCSearchBarTextDidBeginEditing:self];
    }
   
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBarShouldEndEditing:)]) {
         return [self.delegate OCSearchBarShouldEndEditing:self];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBarTextDidEndEditing:)]) {
         [self.delegate OCSearchBarTextDidEndEditing:self];
    }
}

- (BOOL)textField:(UITextField *)textField
            shouldChangeCharactersInRange:(NSRange)range
            replacementString:(NSString *)string {
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBar:shouldChangeTextInRange:replacementText:)]) {
         return [self.delegate OCSearchBar:self shouldChangeTextInRange:range replacementText:string];
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBarSearchButtonClicked:)]) {
         [self.delegate OCSearchBarSearchButtonClicked:self];
    }
    return YES;
}

- (void)OCSearchBarDidChange:(NSNotification *)notification {
    UITextField *textField = [notification object];
    if (self.delegate && [self.delegate respondsToSelector:@selector(OCSearchBar:textDidChange:)]) {
         [self.delegate OCSearchBar:self textDidChange:textField.text];  
    }
}

@end

转载于:https://www.cnblogs.com/xukunhenchouchang/p/5002661.html

使用UITextField去自定义searchBar 【iOS】相关推荐

  1. ZZCustomAlertView - 一个高度自定义的iOS模态弹窗

    2019独角兽企业重金招聘Python工程师标准>>> 这是一个可以高度自定义的iOS模态弹窗 (modal alert view). 项目地址:https://github.com ...

  2. UITabBar和UINavigation组合使用与自定义样式(iOS)

    UITabBarController和UINavigationController组合使用与自定义样式(iOS) 源代码github地址:https://github.com/zcsoft/ZCTab ...

  3. 用css去自定义页面滚动条的样式(谷歌浏览器,PC端)

    用css去自定义页面滚动条的样式(谷歌浏览器,PC端) 常用的自定义滚动条样式,只需要用到三个属性 1.::-webkit-scrollbar 2.::-webkit-scrollbar-track ...

  4. iOS之UITextField怎么自定义键盘的return键

    //初始化textfield并设置位置及大小 UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, ...

  5. 我常去逛的iOS干货文章、blog等

    俗话说,三人行必有我师焉. 总有些知识别人知道,你是不知道的. 感谢开源,感谢分享.我们学习才不会走太多弯路. 所以才会有如此多的好blog.好文章. 以下网站不分排序. 1.1. 喵神-OneV's ...

  6. iOS开发-自定义UIAlterView(iOS 7)

    App中不可能少了弹框,弹框是交互的必要形式,使用起来也非常简单,不过最近需要自定义一个弹框,虽然iOS本身的弹框已经能满足大部分的需求,但是不可避免还是需要做一些自定义的工作.iOS7之前是可以自定 ...

  7. 微信自定义分享ios无效

    微信自定义分享无效情况有很多种,这里记录开发中遇到的一种 分享链接包含汉字 在自定义分享中,分享链接包含汉字,且没有进行编码处理,会导致ios无效:因为Android会自行进行处理,ios却不会,导致 ...

  8. 微信公众号自定义分享IOS失效

    微信公众号自定义分享在IOS端遇到的问题:设置的分享链接如果和当前页面的url不一致就会失效,打开后白页. 解决思路:首先保证分享出去的页面都可以正常访问,然后在路由做页面访问限制,一般情况下,我们希 ...

  9. 王者荣耀进不去服务器维护中,王者荣耀苹果版更新后进不去 王者荣耀iOS版服务器维护怎么办...

    随着7月4日王者荣耀停机维护公告推出后,不少玩家开始更新游戏,但iOS用户反映,安卓手机用户早早就进入了游戏,并开始练习元歌这款新英雄,而自己更新王者荣耀后,一直服务器正在维护中,这是怎么回事呢? 王 ...

  10. html 自定义标签 ios,iOS标签 | 菜鸟教程

    标签的使用 标签用于显示静态内容,包括单独的一行或多行. 重要的属性 textAlignment textColor text numberOflines lineBreakMode 添加自定义方法  ...

最新文章

  1. hbase 客户端_HBase架构与原理详解
  2. Cannot complete the install because one or more required items could not be found.
  3. 家门口的医疗新体验,网易云信携手嘉虹健康打造互联网医院新场景
  4. hdu 1058 Humble Numbers
  5. django-反向查询-后端反向-前端反向
  6. python如何把二进制转文本_在python3中如何把文本转换为二进制
  7. Centos7 网络配置 设置静态Ip
  8. 参考:创业公司搭建自己的技术架构
  9. android开发中悬浮窗被禁用,无权限开启悬浮窗的解决方案
  10. [007]爬虫系列 | RPC调用简单示例
  11. Day715. 适配不同的类型的switch匹配 -Java8后最重要新特性
  12. 2021年浙大考研计算机专业录取分数线,2021年浙江大学研究生录取分数线是多少...
  13. 网传宝塔“0day”挂马事件—附检测脚本
  14. 九阴真经战无不胜服务器位置,九阴真经新服“战无不胜”
  15. unity开发_Unity开发人员在Ludum Dare 30上大放异彩
  16. 网上商城建设:微信小程序直播申请开通流程及开通方法
  17. 人工神经网络的发展前景,人工神经网络及其应用
  18. Ubuntu 16.04卸载LibreOffice等不常用软件
  19. dhu 2.3 阿姆斯特朗数
  20. 大前端 - 微信小程序

热门文章

  1. Lync Server 2013 实战系列之五:标准版-定义拓扑生成器
  2. 数论知识(2)-------------欧拉函数
  3. Some Important Data Structures
  4. [转]Javascript 中 String.replace( ) 的妙用
  5. vim 复制到剪切板
  6. GitHub 40000星!收下这份宇宙最强「程序员装备指南」
  7. JDK 14 性能提升,但 JDK 8 仍是最强王者!
  8. 将Java EE单体应用打造成微服务
  9. 月薪 1 万和 10 万的人,到底差在哪儿?
  10. django数据库操作