[英]UITextView resize when keyboard is open calculation
打開鍵盤時,我正在嘗試調整UITextView
大小。
為了給我的UITextView
一個新的大小(以便它不會被鍵盤遮蓋),我進行以下計算
firstResult = UITextView bottom coordinate - keyboard top coordinate
firstResult
現在應該具有陰影的UITextView frame
的大小
然后我做textView.frame.size.height -= firstResult
現在應該有一個不會被鍵盤textView.frame.size.height -= firstResult
的新大小。
突出的代碼問題在於,UIView的始終始終隱藏在鍵盤后面。
誰能指出我的計算出了什么問題,以便新的尺寸總是正確的? 或我可以用來適當調整UITextView大小的任何其他方式,因為我在網上找到的所有示例均無法正常工作。
編碼
- (void)keyboardWasShown:(NSNotification *)notification {
CGRect viewFrame = input.frame;
CGFloat textEndCord = CGRectGetMaxY(input.frame);
CGFloat kbStartCord = input.frame.size.height - ([[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]).size.height;
CGFloat result = fabsf( input.frame.size.height - fabsf( textEndCord - kbStartCord ));
viewFrame.size.height -= result;
NSLog(@"Original Height:%f, TextView End Cord: %f, KB Start Cord: %f, resutl: %f, the sum: %f",input.frame.size.height, textEndCord,kbStartCord,result,fabsf( textEndCord - kbStartCord ));
input.frame = viewFrame;
}
計算存在問題,請嘗試執行此操作,
- (void)keyboardWasShown:(NSNotification *)notification {
CGRect viewFrame = input.frame;
CGFloat textEndCord = CGRectGetMaxY(input.frame);
CGFloat kbStartCord = textEndCord - ([[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]).size.height;
viewFrame.size.height = kbStartCord;
input.frame = viewFrame;
}
編輯
通用公式也支持橫向模式
- (void)keyboardWasShown:(NSNotification *)notification {
CGFloat keyboardHeight;
CGRect viewFrame = textView.frame;
CGFloat textMaxY = CGRectGetMaxY(textView.frame);
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
keyboardHeight = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.width;
} else {
keyboardHeight = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
}
CGFloat maxVisibleY = self.view.bounds.size.height - keyboardHeight;
viewFrame.size.height = viewFrame.size.height - (textMaxY - maxVisibleY);
textView.frame = viewFrame;
}
我不得不添加UIInterfaceOrientationIsLandscape
條件,因為[[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
設備在橫向上時不起作用。 我知道這有點棘手,解決該問題的另一種方法是檢測設備旋轉並更改參數值。 它是由你決定。
公式說明
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.