這篇文章主要介紹了iOS如何實現防鍵盤遮擋,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

當我們在UITextField輸入數據時經常彈出鍵盤遮擋界面,解決方法是:在彈出鍵盤時將整個UIVIew向上移動,在鍵盤消失時,UIVIew還原。
實例代碼如下:
@interface ViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)UITextField* tf;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tf = [[UITextField alloc]initWithFrame:CGRectMake(10, 600, 100, 20)];
self.tf.delegate = self;
self.tf.backgroundColor = [UIColor blackColor];
[self.view addSubview:self.tf];
}
#pragma mark life Circle
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//后臺切換到前臺通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground)name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[self.view endEditing:YES];
}
- (void)applicationWillEnterForeground{
[self.view endEditing:YES];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
#pragma mark UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
//第一個cell不往上彈輸入框的位置
// if(indexPath.row!=0){
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
// }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
}
#pragma mark 鍵盤操作
- (void)keyboardWillChange:(NSNotification *)note
{
NSDictionary *userInfo = note.userInfo;
CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
//這個64是我減去的navigationbar加上狀態欄20的高度,可以看自己的實際情況決定是否減去;
CGFloat moveY = keyFrame.origin.y -self.tf.frame.origin.y-self.tf.frame.size.height;
NSLog(@"%f",moveY);
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, moveY);
}];
}
- (void)keyboardWillHide:(NSNotification *)nsnotification
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
[UIView animateWithDuration:0.2 animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, 0);
}];
}
@end感謝你能夠認真閱讀完這篇文章,希望小編分享的“iOS如何實現防鍵盤遮擋”這篇文章對大家有幫助,同時也希望大家多多支持創新互聯建站,關注創新互聯網站建設公司行業資訊頻道,更多相關知識等著你來學習!
另外有需要云服務器可以了解下創新互聯建站www.yijiale78.com,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
分享名稱:iOS如何實現防鍵盤遮擋-創新互聯
URL地址:http://www.yijiale78.com/article22/phsjc.html
成都網站建設公司_創新互聯,為您提供網站排名、外貿網站建設、自適應網站、云服務器、營銷型網站建設、小程序開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯