简单注册界面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;
        }
    
    };
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

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

友情链接更多精彩内容