使自定义视图在旋转设备时粘到键盘的顶部
我的应用程序只有iPad,根视图embedded在具有两个子视图的导航控制器中:
1) UITextView
(不是UITextField
),覆盖除导航栏外的整个区域。
2)另一个UIView
作为工具栏。 它覆盖了UITextView,并且最初停留在根视图的底部。
现在我可以使“工具栏”与虚拟键盘同步上下。
但是有一个问题:如果我在键盘显示的时候旋转了设备,那么“工具栏”不再粘在虚拟键盘的顶部,而是在旋转和落下的时候停留在屏幕的中间以便与键盘相遇旋转后 ,这是相当丑陋的。
目前我通过dynamic添加和删除约束来使工具栏视图上下移动,我不确定这是否是一个问题,因为我只使用模拟器进行testing。
任何人都可以给我一些build议吗?
在底部应用程序中带有工具栏的这种UITextView的例子可以是Document Pro或Pages 。
我将推荐使用UITextView
inputAccessoryView
属性。
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;
只需用上面的方法,你将会在工具栏上粘贴一个工具栏,在旋转的时候它会有一个很好的和平滑的animation。 我没有看到你引用的其他应用程序,但我相信这是他们在页面中使用。
作为替代,您可以手动布局您的工具栏而不应用约束。 为此,您可以:
添加方法来处理键盘出现。
[[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 +中,取决于方向, width
和height
有不同的值。
为了确保您的自定义布局方法( layoutElements
)被调用,您还可以将其放在viewWillLayoutSubviews
方法中。
- (void) viewWillLayoutSubviews { [super viewWillLayoutSubviews]; [self layoutElements]; }