2013-09-05 34 views
0

我试图在键盘打开时调整UITextView的大小。当键盘打开时,UITextView调整大小

为了给我UITextView新的大小(以使其不会成为键盘阴影)我做如下计算

firstResult = UITextView bottom coordinate - keyboard top coordinate 

firstResult现在应该有阴影UITextView frame

的大小

然后我做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; 
} 

+0

在您的NSLog显示的结果的预期? – CoderPug

+0

Nop,我的方程式中缺少一些东西,因为我从来没有得到正确的尺寸 –

回答

4

上有一个计算问题,尝试此相反,

- (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;当设备处于景观不起作用。我知道这有点棘手,另一种解决方法是检测设备旋转并更改参数的值。它是由你决定。

公式解释

enter image description here

+0

这是两行太大 –

+0

实际上,这对iOS6,但不是iOS 7有效:S –

+0

您的'info'从哪里来?我刚编辑我的答案 – CoderPug

相关问题