效果图如下:

奉上代码:
.h 文件
//
// UITextField+KeyboardAccessoryView.h
// SingleProject
//
// Created by devmao on 2018/10/4.
// Copyright © 2018年 devmao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UITextField (KeyboardAccessoryView)
/**
自定义AccessoryView
*/
@property(strong, nonatomic) UIView * customAccessoryView;
/**
是否隐藏自定义AccessoryView
*/
@property(nonatomic) BOOL isHiddenCustomAccessoryView;
@end
.m文件代码:
//
// UITextField+KeyboardAccessoryView.m
// SingleProject
//
// Created by devmao on 2018/10/4.
// Copyright © 2018年 devmao. All rights reserved.
//
#import "UITextField+KeyboardAccessoryView.h"
#import <objc/runtime.h>
@implementation UITextField (KeyboardAccessoryView)
- (UIView *)inputAccessoryView{
if (self.isHiddenCustomAccessoryView) {
return [[UIView alloc]init];
}
if (self.customAccessoryView) {
return self.customAccessoryView;
}
return [self creatCustomAccessoryView];
}
#pragma mark - event response
- (void)resignKeyBoardResponse{
[self endEditing:YES];
}
#pragma mark - private method
- (UIView *)creatCustomAccessoryView{
UIToolbar * toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
UIBarButtonItem * space1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * space2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyBoardResponse)];
[toolBar setItems:@[space1, space2, doneBtn]];
return toolBar;
}
#pragma mark - setters && getters
- (void)setCustomAccessoryView:(UIView *)customAccessoryView{
objc_setAssociatedObject(self, @selector(customAccessoryView), customAccessoryView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)customAccessoryView{
//_cmd 表示当前方法的selector
return objc_getAssociatedObject(self, _cmd);
}
- (void)setIsHiddenCustomAccessoryView:(BOOL)isHiddenCustomAccessoryView{
objc_setAssociatedObject(self, @selector(isHiddenCustomAccessoryView), @(isHiddenCustomAccessoryView), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isHiddenCustomAccessoryView{
NSNumber * num = objc_getAssociatedObject(self, _cmd);
return (num && [num isKindOfClass:NSNumber.self]) ? [num boolValue] : NO;
}
@end
over
网友评论