简单注册界面block实现

// 工具条
// LZKeyboardTool.h
#import <UIKit/UIKit.h>

typedef enum {
    KeyboardItemTypePrevious, // 上一个
    KeyboardItemTypeNext, // 下一个
    KeyboardItemTypeDone // 完成
} KeyboardItemType;

// 定义一个类型
typedef void (^myBlock)(KeyboardItemType);

@interface LZKeyboardTool : UIView

+ (instancetype)keyboardTool;

@property (nonatomic, copy) myBlock pBlock;

@end

// LZKeyboardTool.m
#import "LZKeyboardTool.h"

@interface LZKeyboardTool()

@end

@implementation LZKeyboardTool

// 上一个
- (IBAction)previous:(id)sender {
    if (_pBlock) { // 先判断
        _pBlock(KeyboardItemTypePrevious); // 调用block
    }
}

// 下一个
- (IBAction)next:(id)sender {
    if (_pBlock) {
        _pBlock(KeyboardItemTypeNext);
    }
}
// 完成
- (IBAction)done:(id)sender {
    if (_pBlock) {
        _pBlock(KeyboardItemTypeDone);
    }
}

+ (instancetype)keyboardTool{
    return [[[NSBundle mainBundle] loadNibNamed:@"LZKeyboardTool" owner:nil options:nil] lastObject];
}

@end

HMKeyboardTool.xib图:

// ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

// ViewController.m
#import "ViewController.h"
#import "LZKeyboardTool.h"

@interface ViewController () //<LZKeyboardToolDelegate>
{
    NSArray *_fields; // 存储所有的textField
}

// 生日框
@property (weak, nonatomic) IBOutlet UITextField *birthdayField;
// 输入框容器
@property (weak, nonatomic) IBOutlet UIView *inputContainer;
/** LZKeyboard数据*/
@property (nonatomic, strong) LZKeyboardTool *tool;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.初始化自定义键盘
    [self setupCustomKeyboard];

    // 创建自定义键盘
    self.tool = [LZKeyboardTool keyboardTool];

    // 2.设置每一个textfield的键盘工具view(inputAccessoryView)
    [self setupKeyboardTool];

    // 3.监听键盘的事件
    [self setupKeyboardNotification];

    // 含义,弱引用,防止循环引用
    __weak typeof(self) weakSelf = self;

    // 用block保存一段代码
    self.tool.pBlock = ^ (KeyboardItemType itemType){
        // 获取当前响应者的索引
        int currentIndex = [weakSelf getCurrentResponderIndex];

        switch (itemType) {
            case KeyboardItemTypePrevious:
                NSLog(@"上一个");
                [weakSelf showPreviousField:currentIndex];
                break;
            case KeyboardItemTypeNext:
                [weakSelf showNextField:currentIndex];
                break;
            case KeyboardItemTypeDone:
                [weakSelf touchesBegan:nil withEvent:nil];
                break;
        }

    };

}

// 获取当前textField的响应者索引
// 如果返回-1代理没有找到响应者
- (int)getCurrentResponderIndex
{
    // 遍历所有的textField获取响应者
    for (UITextField *tf in _fields) {
        if (tf.isFirstResponder) {
            return [_fields indexOfObject:tf];
        }
    }
    return -1;
}

// 1.初始化自定义键盘
- (void)setupCustomKeyboard
{
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];

    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    datePicker.datePickerMode = UIDatePickerModeDate;

    self.birthdayField.inputView = datePicker;
}

// 2.设置每一个textfield的键盘工具view(inputAccessoryView)
- (void)setupKeyboardTool
{
    // 创建工具栏
    LZKeyboardTool *tool = self.tool;

    // 1.获取输入框窗口的所有子控件
    NSArray *views = self.inputContainer.subviews;

    // 创建一个数据存储textfield
    NSMutableArray *fieldsM = [NSMutableArray array];

    // 2.遍历
    for (UIView *child in views) {
        // 如果子控制器是UITextField的时候,设置inputAccessoryView
        if ([child isKindOfClass:[UITextField class]]) {
            UITextField *tf = (UITextField *)child; // 类型转换
            tf.inputAccessoryView = tool;
            [fieldsM addObject:tf];
        }
    }

    _fields = fieldsM;

}

- (void)setupKeyboardNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)dealloc{
    // 删除在控制器上的通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)kbFrameChange:(NSNotification *)notifi
{
//    NSLog(@"%@", notifi);
//    NSLog(@"%@", notifi.userInfo[@"UIKeyboardFrameEndUserInfoKey"]);
    // 获取键盘改变的y值
    // 键盘结束时的fm
    CGRect kbEndFrm = [notifi.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];

    // 键盘结束时的y
    CGFloat kEndY = kbEndFrm.origin.y;

    // 获取当前的响应者
    int currentIndex = [self getCurrentResponderIndex];
    UITextField *currentTf = _fields[currentIndex];
    int inputY = self.inputContainer.frame.origin.y;
    CGFloat tfMaxY = CGRectGetMaxY(currentTf.frame) + inputY;
    NSLog(@"kEndY = %f, tfMaxY = %f, inputY = %d", kEndY, tfMaxY, inputY);
    // 改变控制器view的transform
    if (tfMaxY > kEndY) {
        self.view.transform = CGAffineTransformMakeTranslation(0, kEndY - tfMaxY);
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.view.transform = CGAffineTransformIdentity; // 恢复到原来位置
        }];
    }

}

#pragma mark -键盘工具条的代理

// 让上一个field成为响应者
- (void)showPreviousField:(int) currentIndex{
    int previousIndex = currentIndex - 1;
    if (previousIndex >= 0) {
        UITextField *previousTf = [_fields objectAtIndex:previousIndex];
        [previousTf becomeFirstResponder];
    }
}
// 让下一个field成为响应者
- (void)showNextField:(int) currentIndex{
    int nextIndex = currentIndex + 1;
    if (nextIndex < _fields.count) {
        UITextField *nextTf = [_fields objectAtIndex:nextIndex];
        [nextTf becomeFirstResponder];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];

    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformIdentity; // 恢复到原来位置
    }];
}

@end

效果图片:

笔者认为这里block使用需要注意的是:

  • block里面保存了一段代码,里面用到了控制器的self,那么为了避免循环引用,需要使用下面一段代码

    // 含义,弱引用,防止循环引用
    __weak typeof(self) weakSelf = self;
    
  • 调用block代码的时候需要进行判断

    // 上一个
    - (IBAction)previous:(id)sender {
    if (_pBlock) { // 先判断
        _pBlock(KeyboardItemTypePrevious); // 调用block
    }
    }
    
  • block保存一段代码可以这样写:

    // 用block保存一段代码
    self.tool.pBlock = ^ (KeyboardItemType itemType){
        // 获取当前响应者的索引
        int currentIndex = [weakSelf getCurrentResponderIndex];
        
        switch (itemType) {
            case KeyboardItemTypePrevious:
                NSLog(@"上一个");
                [weakSelf showPreviousField:currentIndex];
                break;
            case KeyboardItemTypeNext:
                [weakSelf showNextField:currentIndex];
                break;
            case KeyboardItemTypeDone:
                [weakSelf touchesBegan:nil withEvent:nil];
                break;
        }
    
    };
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • 禅与 Objective-C 编程艺术 (Zen and the Art of the Objective-C C...
    GrayLand阅读 1,595评论 1 10
  • 实现目标,给键盘添加一个工具条 LZKeyboardTool.xib图: 效果图片: 笔者主要是想通过该示例程序来...
    Z了个L阅读 463评论 0 2
  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 5,144评论 1 23
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,670评论 0 9
  • 第一篇第二篇大概是把下载图片缓存图片的这个逻辑走完了,里面涉及好多类。 罗列一下 UIView+WebCache ...
    充满活力的早晨阅读 729评论 0 1