簡單注冊界面block實現(xiàn)

// 工具條
// 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); // 調(diào)用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數(shù)據(jù)*/
@property (nonatomic, strong) LZKeyboardTool *tool;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.初始化自定義鍵盤
    [self setupCustomKeyboard];

    // 創(chuàng)建自定義鍵盤
    self.tool = [LZKeyboardTool keyboardTool];

    // 2.設置每一個textfield的鍵盤工具view(inputAccessoryView)
    [self setupKeyboardTool];

    // 3.監(jiān)聽鍵盤的事件
    [self setupKeyboardNotification];

    // 含義,弱引用,防止循環(huán)引用
    __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
{
    // 創(chuàng)建工具欄
    LZKeyboardTool *tool = self.tool;

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

    // 創(chuàng)建一個數(shù)據(jù)存儲textfield
    NSMutableArray *fieldsM = [NSMutableArray array];

    // 2.遍歷
    for (UIView *child in views) {
        // 如果子控制器是UITextField的時候,設置inputAccessoryView
        if ([child isKindOfClass:[UITextField class]]) {
            UITextField *tf = (UITextField *)child; // 類型轉(zhuǎn)換
            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,那么為了避免循環(huán)引用,需要使用下面一段代碼

    // 含義,弱引用,防止循環(huán)引用
    __weak typeof(self) weakSelf = self;
    
  • 調(diào)用block代碼的時候需要進行判斷

    // 上一個
    - (IBAction)previous:(id)sender {
    if (_pBlock) { // 先判斷
        _pBlock(KeyboardItemTypePrevious); // 調(diào)用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;
        }
    
    };
    
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 禪與 Objective-C 編程藝術 (Zen and the Art of the Objective-C C...
    GrayLand閱讀 1,760評論 1 10
  • 實現(xiàn)目標,給鍵盤添加一個工具條 LZKeyboardTool.xib圖: 效果圖片: 筆者主要是想通過該示例程序來...
    Z了個L閱讀 515評論 0 2
  • iOS網(wǎng)絡架構討論梳理整理中。。。 其實如果沒有APIManager這一層是沒法使用delegate的,畢竟多個單...
    yhtang閱讀 5,466評論 1 23
  • 轉(zhuǎn)至元數(shù)據(jù)結尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,030評論 0 9
  • 第一篇第二篇大概是把下載圖片緩存圖片的這個邏輯走完了,里面涉及好多類。 羅列一下 UIView+WebCache ...
    充滿活力的早晨閱讀 841評論 0 1

友情鏈接更多精彩內(nèi)容