关于Block回调的简单应用

在最近的学习中经常会遇到关于Block回调的应用,所以总结一下关于Block回调的基本用法:

1、业务逻辑:在主页面中添加一个搜索视图控件(XBRSearchBar),当开始编辑搜索栏时,通过Block回调跳转至新的页面;

2、Class说明:
a、XBRSearchBar:视图控件,继承UISearchBar;在该类中添加Block属性,系统默认会生成Block属性的set和get方法,在实际使用时,可以根据实际业务逻辑需要重写Block的set和get方法(我这测试的比较简单,就不重写直接使用默认的方法了),而Block的具体实现也不用写,而是放在视图控制器中实现;
b、ViewController:视图控制器,可以根据实际需要添加Block的具体实现;
c、XBRSearchViewController:视图控制器,用于管理跳转后的新视图,与Block的回调没关系了;

3、相关的测试代码如下:

#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

4、具体的完整代码可参考:链接描述

    原文作者:Wingoc
    原文地址: https://segmentfault.com/a/1190000005365254
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞