在最近的學習中常常會遇到關於Block回調的應用,因此總結一下關於Block回調的基本用法:git
一、業務邏輯:在主頁面中添加一個搜索視圖控件(XBRSearchBar),當開始編輯搜索欄時,經過Block回調跳轉至新的頁面;github
二、Class說明:
a、XBRSearchBar:視圖控件,繼承UISearchBar;在該類中添加Block屬性,系統默認會生成Block屬性的set和get方法,在實際使用時,能夠根據實際業務邏輯須要重寫Block的set和get方法(我這測試的比較簡單,就不重寫直接使用默認的方法了),而Block的具體實現也不用寫,而是放在視圖控制器中實現;
b、ViewController:視圖控制器,能夠根據實際須要添加Block的具體實現;
c、XBRSearchViewController:視圖控制器,用於管理跳轉後的新視圖,與Block的回調不要緊了;學習
三、相關的測試代碼以下:測試
#import <UIKit/UIKit.h> @interface XBRSearchBar : UISearchBar <UISearchBarDelegate> // 添加Block屬性(返回值爲:void, 不帶參數) @property (nonatomic, copy) void (^searchBarShouldBeginEditingBlock)(); @end
#import "XBRSearchBar.h" @implementation XBRSearchBar // UISearchBar的代理方法,當開始編輯搜索欄時會調用該方法 - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ // 判斷當Block屬性不爲空時,執行當前Block,就是執行「ViewController」中Block的具體實現代碼 if (_searchBarShouldBeginEditingBlock) self.searchBarShouldBeginEditingBlock(); return YES; } @end
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
#import "ViewController.h" #import "XBRSearchBar.h" #import "XBRSearchViewController.h" @interface ViewController () @property (nonatomic, strong) XBRSearchBar *searchBar; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor purpleColor]; #pragma mark - 設置searchBar視圖 _searchBar = [[XBRSearchBar alloc]init]; _searchBar.delegate = _searchBar; _searchBar.placeholder = @"搜索欄"; _searchBar.backgroundColor = [UIColor clearColor]; _searchBar.showsCancelButton = YES; self.navigationItem.titleView = _searchBar; #pragma mark - block回調跳轉頁面 // 弱化self,避免循環引用; __weak typeof(self) weakSelf = self; XBRSearchViewController *searchViewController = [[XBRSearchViewController alloc]init]; // Block的具體實現; _searchBar.searchBarShouldBeginEditingBlock = ^{ [weakSelf.navigationController pushViewController:searchViewController animated:YES]; }; } @end
// 如下只是跳轉到新頁面的一些界面設置,有興趣能夠瀏覽一下 #import <UIKit/UIKit.h> @interface XBRSearchViewController : UIViewController @end
#import "XBRSearchViewController.h" #import "XBRSearchBar.h" @interface XBRSearchViewController() @property (nonatomic, strong) XBRSearchBar *searchBar; @end @implementation XBRSearchViewController - (void) viewDidLoad{ [super viewDidLoad]; self.view.backgroundColor = [UIColor orangeColor]; _searchBar = [[XBRSearchBar alloc]init]; _searchBar.placeholder = @"搜索欄"; _searchBar.showsCancelButton = YES; self.navigationItem.titleView = _searchBar; } @end
四、具體的完整代碼可參考:連接描述atom