根据设备的方向,我的键盘有两种略有不同的布局。当我首先加载键盘时,它看起来很好。这是肖像版本:
初始约束设置发生在-viewDidLoad(UIInputViewController子类的)中
portraitConstraints = [self constraintsForOrientation:UIInterfaceOrientationPortrait];
landscapeConstraints = [self constraintsForOrientation:UIInterfaceOrientationLandscapeRight];
[self.view addConstraints:portraitConstraints];
[self.view addConstraints:landscapeConstraints];
if ([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height) {
[NSLayoutConstraint deactivateConstraints:landscapeConstraints];
} else {
[NSLayoutConstraint deactivateConstraints:portraitConstraints];
}
此部分有效,因为无论初始方向如何,它都能正确加载。但是,一旦我旋转设备,一切都会出错。
然后回到肖像:
作为参考,正确的横向版本如下所示:
我更新了-updateViewConstraints中的约束,如下所示:
- (void)updateViewConstraints {
if ([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height) {
[NSLayoutConstraint deactivateConstraints:landscapeConstraints];
[NSLayoutConstraint activateConstraints:portraitConstraints];
} else {
[NSLayoutConstraint deactivateConstraints:portraitConstraints];
[NSLayoutConstraint activateConstraints:landscapeConstraints];
}
[super updateViewConstraints];
}
似乎在视图更改后它突然占用的不仅仅是全屏而不仅仅是键盘区域。我有什么想法可以解决这个问题吗?感谢。
答案 0 :(得分:2)
该问题似乎与隐式覆盖包含键盘的视图的高度有关。虽然我没有看到任何会强制调整容器视图大小的内容,但明确设置容器视图的高度可以恢复到良好的,可重现的结果。
我想到了从Apple's App Extension Programming Guide: Custom Keyboard手动限制键盘的高度。
具体而言,相关信息是:
您可以使用“自动布局”调整自定义键盘主视图的高度。默认情况下,根据屏幕大小和设备方向,自定义键盘的大小可与系统键盘匹配。系统始终将自定义键盘的宽度设置为等于当前屏幕宽度。要调整自定义键盘的高度,请更改其主视图的高度约束。
以下代码行显示了如何定义和添加此类约束:
CGFloat _expandedHeight = 500;
NSLayoutConstraint *_heightConstraint =
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeHeight
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 0.0
constant: _expandedHeight];
[self.view addConstraint: _heightConstraint];
注意强>
在iOS 8.0中,您可以在主视图最初在屏幕上绘制后随时调整自定义键盘的高度。
以下是基于此信息的模板答案中的重要方法:
- (void)updateViewConstraints {
if (self.keyboardHeightConstraint == nil) {
// Just starting with SOME value for the height
self.keyboardHeightConstraint =
[NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0.0f
constant:500.0f];
[self.view addConstraint:self.keyboardHeightConstraint];
}
// Obviously, these values will be changed based on device AND orientation
// These are bogus values...
if ([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height) {
self.keyboardHeightConstraint.constant = 300.0f;
[NSLayoutConstraint deactivateConstraints:self.landscapeConstraints];
[NSLayoutConstraint activateConstraints:self.portraitConstraints];
} else {
self.keyboardHeightConstraint.constant = 400.0f;
[NSLayoutConstraint deactivateConstraints:self.portraitConstraints];
[NSLayoutConstraint activateConstraints:self.landscapeConstraints];
}
[super updateViewConstraints];
}