iOS屏幕根据键盘自动变化高度

时间:2021-05-02

一、效果图

二、代码

viewcontroller.h

? 1 2 3 4 5 6 #import <uikit/uikit.h> @interface viewcontroller : uiviewcontroller <uitextfielddelegate> @end

viewcontroller.m

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 #import "viewcontroller.h" #define w [uiscreen mainscreen].bounds.size.width #define h [uiscreen mainscreen].bounds.size.height @interface viewcontroller () @end @implementation viewcontroller - (void)viewdidload { [super viewdidload]; // do any additional setup after loading the view, typically from a nib. uitextfield *field=[[uitextfield alloc]initwithframe:cgrectmake(100, 300, 50, 50)]; field.backgroundcolor=[uicolor redcolor]; field.delegate=self; [self.view addsubview:field]; } #pragma -mark -uitextfielddelegate -(bool)textfieldshouldreturn:(uitextfield *)textfield { [textfield resignfirstresponder]; //self.view 恢复原位 nstimeinterval animationduration=0.10f; [uiview beginanimations:@"resizeforkeyboard" context:nil]; [uiview setanimationduration:animationduration]; float width = w; float height = h; float y = 0.0f; cgrect rect=cgrectmake(0.0f,y,width,height); self.view.frame=rect; [uiview commitanimations]; return yes; } -(bool)textfieldshouldbeginediting:(uitextfield *)textfield { nstimeinterval animationduration=0.30f; [uiview beginanimations:@"resizeforkeyboard" context:nil]; [uiview setanimationduration:animationduration]; float width = w; float height = h; //上移100个单位,按实际情况设置 cgrect rect=cgrectmake(0.0f,-100,width,height); self.view.frame=rect; [uiview commitanimations]; return yes; } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of any resources that can be recreated. } @end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章