【发布时间】:2013-08-28 04:59:56
【问题描述】:
我有一个UIViewCOntroller,其中包含一个UITextView。当键盘出现时,我会像这样调整它的大小:
#pragma mark - Responding to keyboard events
- (void)keyboardDidShow:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
CGRect keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect newTextViewFrame = self.textView.frame;
newTextViewFrame.size.height -= keyboardSize.size.height + 70;
self.textView.frame = newTextViewFrame;
self.textView.backgroundColor = [UIColor yellowColor];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
CGRect keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect newTextViewFrame = self.textView.frame;
newTextViewFrame.size.height += keyboardSize.size.height - 70;
self.textView.frame = newTextViewFrame;
}
textView 似乎调整到正确的大小,但是当用户键入时,光标最终会出现在 textView 框架的“外部”。见下图:
黄色区域是UITextView框(不知道R键旁边的蓝线是什么)。我觉得这很有线。如果这有什么不同,我正在使用 iOS7。
有什么想法或提示吗?
更新
我有一个 UITextView 子类,它使用以下方法绘制水平线(如果有什么不同的话):
- (void)drawRect:(CGRect)rect {
//Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the line color and width
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:229.0/255.0 green:244.0/255.0 blue:255.0/255.0 alpha:1].CGColor);
CGContextSetLineWidth(context, 1.0f);
//Start a new Path
CGContextBeginPath(context);
//Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
NSUInteger numberOfLines = (self.contentSize.height + rect.size.height) / self.font.lineHeight;
CGFloat baselineOffset = 6.0f;
//iterate over numberOfLines and draw each line
for (int x = 0; x < numberOfLines; x++) {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, rect.origin.x, self.font.lineHeight*x + 0.5f + baselineOffset);
CGContextAddLineToPoint(context, rect.size.width, self.font.lineHeight*x + 0.5f + baselineOffset);
}
// Close our Path and Stroke (draw) it
CGContextClosePath(context);
CGContextStrokePath(context);
}
【问题讨论】:
-
我遇到了同样的问题。似乎
textView.font.lineHeight没有考虑调整contentOffset。更正偏移委托的textViewDidChange:不起作用,因为它的值会以某种方式恢复。 -
好的,你是怎么解决的?
-
这可能只是某个未发布的、NDA 的 SDK 的问题吗?它是否适用于其他 iOS 版本?
-
这只是一种预感,但您是否尝试过在您的 keyboardDidShow 和 keyboardWillHide 方法中调用
[self.textView setNeedsLayout];? -
我的第二个想法是:如果您使用的是 AutoLayout,请尝试设置高度约束。将该约束作为 IBOutlet 连接到您的视图控制器。尝试更改自动布局约束,而不是更改框架。请让我知道这是否适合您。
标签: ios objective-c cocoa-touch uitextview uikeyboard