永久解决UITextField键盘遮挡事件-JVTextField

前言

再iOS的开发中,很多时候我们都需要解决TextField的键盘遮挡事件,每次都需要花时间,我们可以使用第三方库来解决,但第三方库很多代码质量参差不齐,而且代码量庞大。本文来分享一个代码量比较小的,有关键注释并且使用简单的JVTextField,你也可以依葫芦画瓢写一个你自己的,后期可以维护的控件。希望本文能帮助到你
代码在Github

截屏.gif

使用方法

拷贝文件到你的工程 JVshowKeyboardManger JVTextField
使用JVTextField 代替 UITextField
指定要移动的moveView self.textField.moveView=self.view;
跳转到下个页面之前要关闭键盘 重点

- (IBAction)pushNextViewController:(UIButton *)sender {
//     跳转到下一页之前 要关闭键盘,不然出现 keyboardToolBar不能隐藏的问题
    [self.view endEditing:YES];
    UIViewController *vc=[[UIViewController alloc]init];
    vc.view.backgroundColor=[UIColor greenColor];
    [self.navigationController pushViewController:vc animated:YES];
}

关键代码

主要由两个类组成

JVTextField : UITextField
JVshowKeyboardManger : NSObject

JVTextField.h
@interface JVTextField : UITextField
/**提供需要移动View层,本质上是可以移动main Window ,但为了个性化的需求,提供配置
*/
@property(nonatomic,weak)UIView* moveView;
@end
JVTextField.m

提供初始化方法


-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    [self Initialize];
    return self;
}
-(instancetype)init{
    self=[super init];
    [self Initialize];
    return self;
}

-(void)awakeFromNib{
    [super awakeFromNib];
    [self Initialize];
}

初始化添加通知


#pragma -mark 初始化
-(void)Initialize{
    [self addTarget:self action:@selector(addKeyboardNotification) forControlEvents:UIControlEventEditingDidBegin];
    [self addTarget:self action:@selector(removeKeyboardNotification) forControlEvents:UIControlEventEditingDidEnd];
}

#pragma -mark添加通知   由单独的一个类来完成
-(void)addKeyboardNotification{
  [JVshowKeyboardManger addNotificationWithTextFiled:self];
}

#pragma -mark 移除通知
-(void)removeKeyboardNotification{
    [JVshowKeyboardManger removeNotificationWithTextFiled:self];
}
JVshowKeyboardManger.h 提供接口
@interface JVshowKeyboardManger : NSObject

+(instancetype)shareClass;

/**添加通知*/
+(void)addNotificationWithTextFiled:(JVTextField*)textFiled;

/**移除通知*/
+(void)removeNotificationWithTextFiled:(JVTextField*)textFiled;

@end

JVshowKeyboardManger.m 提供实现

内部属性和宏定义


#define JVScreen_Width [UIScreen mainScreen].bounds.size.width

#define JVScreen_Height [UIScreen mainScreen].bounds.size.height

#define JVColor(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]

static JVshowKeyboardManger *_sharedClass;

@interface JVshowKeyboardManger()
//为键盘添加一个完成按钮来关闭键盘
@property(strong,nonatomic)UIView* keyboardToolbar;
//moveView 在window中的 rect.origin.y
@property(assign,nonatomic) CGFloat viewY;
// 传递对象  for 遮挡键盘 处理
@property(nonatomic,weak)JVTextField* textFiled;

@end

keyboardToolbar懒加载


-(UIView *)keyboardToolbar{
    if (!_keyboardToolbar) {
        _keyboardToolbar=[[UIView alloc]initWithFrame:CGRectMake(0, JVScreen_Height, JVScreen_Width, 40)];
        _keyboardToolbar.backgroundColor=JVColor(208, 213, 218, 1.0);
        UIButton* complateBtn=[[UIButton alloc]initWithFrame:CGRectMake(JVScreen_Width-35-10, 0, 35, 40)];
        [complateBtn setTitle:@"完成" forState:0];
        [complateBtn setTitleColor:[UIColor blueColor] forState:0];
        complateBtn.titleLabel.font=[UIFont systemFontOfSize:14.f];
        [complateBtn addTarget:self action:@selector(closeTheKeyboard)forControlEvents:UIControlEventTouchUpInside];
        [_keyboardToolbar addSubview:complateBtn];
        NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
        for (UIWindow *window in frontToBackWindows){
            BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
            BOOL windowIsVisible = !window.hidden && window.alpha > 0;
            BOOL windowLevelNormal = window.windowLevel == UIWindowLevelNormal;
            if (windowOnMainScreen && windowIsVisible && windowLevelNormal) {
                [window addSubview:_keyboardToolbar];
                break;
            }
        }
        _keyboardToolbar.alpha=0;
    }
    return _keyboardToolbar;
}

创建单例

+(instancetype)shareClass{
    static dispatch_once_t token;
    dispatch_once(&token,^{
        _sharedClass = [[JVshowKeyboardManger alloc] init];
    });
    return _sharedClass;
}

添加通知

//添加通知
+(void)addNotificationWithTextFiled:(JVTextField*)textFiled{
   JVshowKeyboardManger* thisObject=[JVshowKeyboardManger shareClass];
   thisObject.textFiled=textFiled;
   //计算 moveView 在window中的 rect.origin.y
   thisObject.viewY=[thisObject relativeFrameForScreenWithView:thisObject.textFiled].origin.y;
   [thisObject addKeyboardNotification];
}


//移除通知
+(void)removeNotificationWithTextFiled:(JVTextField*)textFiled{
   JVshowKeyboardManger* thisObject=[JVshowKeyboardManger shareClass];
   [thisObject removeNotification];
}

辅助方法

#pragma -mark 计算moveview 在 window中的 rect
-(CGRect)relativeFrameForScreenWithView:(UIView *)v
{
    UIView *view = v;
    CGFloat x = .0;
    CGFloat y = .0;
    // root  uiwindow  superView ==nil
    while ([view superview])
    {
        x += view.frame.origin.x;
        y += view.frame.origin.y;
        view = view.superview;
        if ([view isKindOfClass:[UIScrollView class]]) {
            x -= ((UIScrollView *) view).contentOffset.x;
            y -= ((UIScrollView *) view).contentOffset.y;
        }
    }
    return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
}

#pragma -mark添加通知
-(void)addKeyboardNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

#pragma -mark 移除通知
-(void)removeNotification{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

处理键盘显示和隐藏


#pragma -mark 键盘显示时
- (void)keyboardWillShow:(NSNotification *)notif {
    if (self.textFiled==nil||self.textFiled.moveView==nil) return;
    CGSize kbSize = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
    CGFloat kbHeight = kbSize.height;
    CGFloat viewY=self.viewY;
    CGFloat viewMaxY=viewY+self.textFiled.frame.size.height;
    CGFloat moveY=viewMaxY+kbHeight-[UIScreen mainScreen].bounds.size.height+40;
    if (moveY>0) {
            self.textFiled.moveView.bounds=CGRectMake(0, moveY, self.textFiled.moveView.frame.size.width, self.textFiled.moveView.frame.size.height);
    }
    self.keyboardToolbar.alpha=1;
    self.keyboardToolbar.frame=CGRectMake(self.keyboardToolbar.frame.origin.x, JVScreen_Height-kbHeight-40, self.keyboardToolbar.frame.size.width, self.keyboardToolbar.frame.size.height);
}
#pragma -mark 键盘隐藏
- (void)keyboardWillHide:(NSNotification *)notif {
    
    self.keyboardToolbar.alpha=0;
    
    [UIView animateWithDuration:0.25 animations:^{
         self.textFiled.moveView.bounds=CGRectMake(0, 0, self.textFiled.moveView.frame.size.width, self.textFiled.moveView.frame.size.height);
        self.keyboardToolbar.frame=CGRectMake(self.keyboardToolbar.frame.origin.x, JVScreen_Height, self.keyboardToolbar.frame.size.width, self.keyboardToolbar.frame.size.height);
    }completion:^(BOOL finished) {
        
    }];
}

点击关闭事件

#pragma -mark 点击关闭键盘
-(void)closeTheKeyboard{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

结束语

是不是很简单呢,你也可以实现一个textView的版本,限于篇幅,本文不在续写

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容