【问题标题】:make custom view stick to top of the keyboard while rotating device旋转设备时使自定义视图粘在键盘顶部
【发布时间】:2015-12-09 13:59:51
【问题描述】:

我的应用仅适用于 iPad,根视图嵌入在具有两个子视图的导航控制器中:

1) 一个UITextView(不是UITextField),覆盖除导航栏以外的整个区域。

2) 另一个UIView 用作工具栏。它覆盖了 UITextView 并最初停留在根视图的底部。

现在我可以让“工具栏”与虚拟键盘同步上下移动。

但是有一个问题:如果我在键盘显示时旋转设备,“工具栏”不再粘在虚拟键盘的顶部,而是停留在虚拟键盘的中间旋转后,屏幕一边旋转,一边掉下来碰到键盘,相当难看。

目前我通过动态添加和删除约束来使 工具栏 视图上下移动,但我不确定这是否是一个问题,因为我只是使用模拟器对其进行测试。 p>

谁能给我一些建议?

这种 UITextView 在底部带有工具栏 应用的示例可能是 Document ProPages

【问题讨论】:

  • 需要更多的屏幕截图说明

标签: ios objective-c ipad ios-simulator


【解决方案1】:

我会推荐使用UITextViewinputAccessoryView 属性。

UIToolbar* toolbar = [[UIToolbar alloc] init];
toolbar.barStyle = UIBarStyleDefault;
toolbar.items = [NSArray arrayWithObjects:
                       [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:nil action:nil],
                       [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:nil action:nil],
                       [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:nil],
                       [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:nil],
                       nil];
[toolbar sizeToFit];
self.textfiled.inputAccessoryView = toolbar;

通过上面的操作,您将在键盘顶部粘贴一个工具栏,并且在旋转过程中它会有一个漂亮流畅的动画。我没有查看您引用的其他应用程序,但我相信这就是他们在Pages 中使用的应用程序。

【讨论】:

  • 你是对的。我应该使用 InputAccessoryView 来实现它,一切都是自动为我完成的,只是它会随着虚拟键盘消失。
  • @Chris 是的,你是对的。工具栏将与键盘一起使用。如果你想在底部有一个单独的工具栏,你需要单独做。
【解决方案2】:

作为替代方案,您可以手动布局工具栏而不应用约束。为此,您可以:

添加处理键盘出现的方法。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)                                               name:UIKeyboardDidShowNotification object:nil];

此方法需要计算当前键盘高度。

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    self.keyboardHeight = MIN(kbSize.height, kbSize.width);
    [self layoutElements];
}

旋转设备时也会调用此方法。

然后在您的自定义layoutElements 方法中,您使用预先计算的键盘高度来定位您的工具栏。

您可以使用根视图的大小或屏幕大小 ([[UIScreen mainScreen] bounds].size),但请注意,在 iOS7 和 iOS8+ 中,widthheight 的值取决于方向。

为确保您的自定义布局方法 (layoutElements) 被调用,您还可以将其放在 viewWillLayoutSubviews 方法中。

- (void) viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self layoutElements];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2019-04-17
    • 2018-09-17
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多