iOS自定義控件-UISearchBar

   在開發過程中,UISearchBar屬不多見的控件,在我們一般使用的是系統原生樣式:


這裏寫圖片描述

   但是UI設計師可能想要的是這種:

這裏寫圖片描述

   可能你覺得很簡單:覺得設置背景顏色,邊框圖標什麼的;
先看設置背景顏色

   我們直接設置backgroundcolor並不生效:因爲這樣直接設置的是最後面一層視圖,前面有層灰色視圖是UISearchBarBackground;
所以使用原生的backgroundColor並不生效,


這裏寫圖片描述

   你發現後可能覺得很簡單:直接設置UISearchBarBackground的背景圖,但是我們看控件

這裏寫圖片描述

   他是一個ImageView,而且直接去設置背景顏色也是不生效的,蘋果只給這個UISearchBarBackground暴露一個setImage接口。所以可以用Image和Color的轉化來設置。

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    self.backgroundImage = [self createImageWithColor:backgroundColor];
}

- (void)setContentInset:(UIEdgeInsets)contentInset
{
   _contentEdgeInsets = contentInset;
   [self setNeedsDisplay];
}

- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

怎樣設置UITextfield屬性:
   對於這個TextField,UISearchBar並沒有給外部使用,但是可以通過視圖層級關係:


這裏寫圖片描述



   我們可以獲取UITextField通過以下方式:這樣我們才能設置輸入字體樣式,對齊方式,光標屬性等。

(1). 通過KVC鍵值獲取;

    self.searchTextField = [self valueForKey:@"_searchField"];

(2). 通過視圖獲取該子視圖;

if (_searchTextField == nil) {
        for(UIView* view in self.subviews)
        {
            for(id subview in view.subviews) {
                if([subview isKindOfClass:[UITextField class]])
                {
                    _searchTextField = subview;
                    return subview;
                }
            }
        }
    }

   對於左側視圖的圖片我們可以設置,但是大小呢?假如想要這樣一個呢?


這裏寫圖片描述


這就需要我們重寫這個控件,我重寫的控件包括以下接口和屬性:

@interface SHSearchBar : UISearchBar


// 搜索輸入框,可進行UITextField操作
// 修改字體大小,編輯代理等;
@property (nonatomic, strong) UITextField *searchTextField;

// 設置搜索框背景顏色;
@property (nonatomic, strong) UIColor *backgroundColor;

/* 設置左側搜索View;
 * 自定義設置搜索圖標視圖。
 * 可以是Button imageView等等。可以通過此View設置搜索圖標frame,樣式,背景等等
 * 設置優先級高於leftSearchIcon;
 */
@property (nonatomic, strong) UIView *leftSearchView;

// 設置左側搜索按鈕的icon,僅修改圖片,
@property (nonatomic, strong) UIImage *searchIcon;

// 設置右側清除按鈕的icon,僅修改圖片,
@property (nonatomic, strong) UIImage *clearIcon;

/* 設置中間編輯區的EdgeInsets,
 * 默認frame.origin == (8.0, 6.0);不等於searchBar的bounds
 * 可通過設置Inset修改Textfild的邊距
 */
@property (nonatomic, assign) UIEdgeInsets contentEdgeInsets;

// 初始化控件
- (instancetype)initWithFrame:(CGRect)frame;

// 設置左側搜索按鈕的偏移量
- (void)setLeftSearchIconOffset:(UIOffset)offset;

// 設置左側搜索按鈕的Rect,自定義佈局
- (void)setLeftSearchIconRect:(CGRect)rect;

// 設置右側清除按鈕的偏移量
- (void)setrithClearIconOffset:(UIOffset)offset;

- (void)setTintColor:(UIColor *)tintColor;

@end

如喜歡,歡迎下載。



我的GitHub代碼地址: https://github.com/lvshaohua/SHSearchBar.git



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章