輸入框隨著鍵盤(pán)彈出上移

有個(gè)功能是點(diǎn)擊輸入框鍵盤(pán)彈出的時(shí)候不讓遮擋辩昆,就是鍵盤(pán)彈起時(shí)輸入框自動(dòng)上移,效果如下:


效果圖

具體實(shí)現(xiàn)代碼:

//  KeyboardToMoveController.m
//  JSOCTest
//
//  Created by 賈倍 on 2018/4/17.
//  Copyright ? 2018年 賈倍. All rights reserved.
//

#import "KeyboardToMoveController.h"

@interface KeyboardToMoveController (){
    UITextField *phoneNemberText;//手機(jī)號(hào)輸入框
    UITextField *verifyCodeText;//密碼輸入框
}

@end

@implementation KeyboardToMoveController

- (void)viewDidLoad {
    [super viewDidLoad];
    phoneNemberText = [[UITextField alloc] initWithFrame:FRAME(100, SCREEN_HEIGHT*0.7, 100, 30)];
    phoneNemberText.placeholder = @"手機(jī)號(hào)";
    phoneNemberText.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:phoneNemberText];
    
    verifyCodeText = [[UITextField alloc] initWithFrame:FRAME(100, phoneNemberText.mr_bottom + 20, 100, 30)];
    verifyCodeText.placeholder = @"密碼";
    verifyCodeText.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:verifyCodeText];
    
    //注冊(cè)觀察鍵盤(pán)的變化
    //鍵盤(pán)將要顯示
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //鍵盤(pán)將要隱藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    // Do any additional setup after loading the view.
}

-(void)keyboardWillShow:(NSNotification *)notification{
    //獲取處于焦點(diǎn)中的view
    NSArray *textFields = @[phoneNemberText, verifyCodeText];
    UIView *focusView = nil;
    for (UITextField *view in textFields) {
        if ([view isFirstResponder]) {
            focusView = view;
            break;
        }
    }
    if (focusView) {
        //獲取鍵盤(pán)彈出的時(shí)間
        double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //獲取鍵盤(pán)上端Y坐標(biāo)
        CGFloat keyboardY = [self getKeyboardY:notification.userInfo];
        //獲取輸入框下端相對(duì)于window的Y坐標(biāo)
        CGPoint tmp = [self getViewOriginPointToWindow:focusView];
        CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
        //計(jì)算二者差值
        CGFloat ty = keyboardY - inputBoxY;
        NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
        //差值小于0鹦肿,做平移變換
        [UIView animateWithDuration:duration animations:^{
            if (ty < 0) {
                self.view.transform = CGAffineTransformMakeTranslation(0, ty);
            }
        }];
    }
}

-(void)keyboardWillHide:(NSNotification *)notification{
    //獲取鍵盤(pán)彈出的時(shí)間
    double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //還原
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

//處理iOS8之后鍵盤(pán)上端的Y坐標(biāo)以及輸入框下端相對(duì)于window的Y坐標(biāo)
-(CGFloat)getKeyboardY:(NSDictionary *)userInfo{
    CGFloat screenHeight;
    CGFloat keyboardY = 0;
    CGFloat keyboardHeight = 0;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (([[[UIDevice currentDevice] systemVersion] floatValue]<8)  && UIInterfaceOrientationIsLandscape(orientation)) {
        screenHeight = [[UIScreen mainScreen] bounds].size.width;
        keyboardHeight = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.width;
        keyboardY = screenHeight - keyboardHeight;
    } else if (([[[UIDevice currentDevice] systemVersion] floatValue]<8)  && UIInterfaceOrientationIsPortrait(orientation)) {
        screenHeight = [[UIScreen mainScreen] bounds].size.height;
        keyboardHeight = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        keyboardY = screenHeight - keyboardHeight;
    } else {
        keyboardY = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    }
    return keyboardY;
}

//獲取輸入框下端的Y坐標(biāo)
-(CGPoint)getViewOriginPointToWindow:(UIView *)view{
    CGPoint origin;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8) {
        CGPoint focusViewPoint = [view convertPoint:CGPointZero toView:nil];
        UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            origin.y = focusViewPoint.x;
            origin.x = [[[UIApplication sharedApplication] delegate] window].bounds.size.height - focusViewPoint.y;
        } else if (orientation == UIInterfaceOrientationLandscapeRight) {
            origin.y = [[[UIApplication sharedApplication] delegate] window].bounds.size.width - focusViewPoint.x;
            origin.x = focusViewPoint.y;
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            origin.y = [[[UIApplication sharedApplication] delegate] window].bounds.size.height - focusViewPoint.y;
            origin.x = [[[UIApplication sharedApplication] delegate] window].bounds.size.width - focusViewPoint.x;
        } else {
            origin = focusViewPoint;
        }
    } else {
        CGRect rect = [view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
        origin = rect.origin;
    }
    return origin;
}

//點(diǎn)擊空白區(qū)域讓鍵盤(pán)回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    for (UIView *view in self.view.subviews) {
        [view resignFirstResponder];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市诫肠,隨后出現(xiàn)的幾起案子泄私,更是在濱河造成了極大的恐慌,老刑警劉巖袜硫,帶你破解...
    沈念sama閱讀 211,348評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件氯葬,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡婉陷,警方通過(guò)查閱死者的電腦和手機(jī)溢谤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,122評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)憨攒,“玉大人,你說(shuō)我怎么就攤上這事阀参「渭” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,936評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵蛛壳,是天一觀的道長(zhǎng)杏瞻。 經(jīng)常有香客問(wèn)我,道長(zhǎng)衙荐,這世上最難降的妖魔是什么捞挥? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,427評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮忧吟,結(jié)果婚禮上砌函,老公的妹妹穿的比我還像新娘。我一直安慰自己溜族,他們只是感情好讹俊,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,467評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著煌抒,像睡著了一般仍劈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上寡壮,一...
    開(kāi)封第一講書(shū)人閱讀 49,785評(píng)論 1 290
  • 那天贩疙,我揣著相機(jī)與錄音讹弯,去河邊找鬼。 笑死这溅,一個(gè)胖子當(dāng)著我的面吹牛组民,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播芍躏,決...
    沈念sama閱讀 38,931評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼邪乍,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了对竣?” 一聲冷哼從身側(cè)響起庇楞,我...
    開(kāi)封第一講書(shū)人閱讀 37,696評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎否纬,沒(méi)想到半個(gè)月后吕晌,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,141評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡临燃,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,483評(píng)論 2 327
  • 正文 我和宋清朗相戀三年睛驳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片膜廊。...
    茶點(diǎn)故事閱讀 38,625評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡乏沸,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出爪瓜,到底是詐尸還是另有隱情蹬跃,我是刑警寧澤,帶...
    沈念sama閱讀 34,291評(píng)論 4 329
  • 正文 年R本政府宣布铆铆,位于F島的核電站蝶缀,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏薄货。R本人自食惡果不足惜翁都,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,892評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谅猾。 院中可真熱鬧柄慰,春花似錦、人聲如沸赊瞬。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)巧涧。三九已至薯蝎,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谤绳,已是汗流浹背占锯。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工袒哥, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人消略。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓堡称,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親艺演。 傳聞我的和親對(duì)象是個(gè)殘疾皇子却紧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,492評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容