1. 程式人生 > >iOS自定義控制元件-UISearchBar

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