使用UITextField去自定義searchBar 【iOS】

查看完整文章請到源地址: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

api

相關文章
相關標籤/搜索