Rob*_*mie 94 iphone keyboard cocoa-touch ios
在某些情况下,我想在iPhone键盘的顶部添加一个工具栏(例如,当您在导航表单元素时,在iPhone Safari中).
目前我正在使用常量指定工具栏的矩形,但是由于界面的其他元素处于不稳定状态 - 工具栏和屏幕顶部的导航栏 - 每次我们进行次要界面更改时,工具栏都会失去对齐.
有没有办法以编程方式确定键盘相对于当前视图的位置?
ton*_*lon 142
从iOS 3.2开始,有一种新方法可以实现这种效果:
UITextFields并UITextViews拥有一个inputAccessoryView属性,您可以将其设置为任何视图,该属性会自动显示在上方并使用键盘进行动画处理.
请注意,您使用的视图既不应该在其他地方的视图层次结构中,也不应该将其添加到某个超级视图中,这是为您完成的.
小智 72
所以基本上:
在init方法中:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object:nil];
Run Code Online (Sandbox Code Playgroud)
然后有上面提到的方法调整条的位置:
-(void) keyboardWillShow:(NSNotification *) note
{
CGRect r = bar.frame, t;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &t];
r.origin.y -= t.size.height;
bar.frame = r;
}
Run Code Online (Sandbox Code Playgroud)
可以通过将位置更改设置为动画来使其变得漂亮
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
//...
[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)
phi*_*phi 60
这是基于tonklon的现有答案 - 我只是添加了一个代码片段,在键盘顶部显示了一个半透明的黑色工具栏,右边是一个"完成"按钮:
UIToolbar *toolbar = [[[UIToolbar alloc] init] autorelease];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];
UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(resignKeyboard)];
NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];
[flexButton release];
[doneButton release];
[toolbar setItems:itemsArray];
[aTextField setInputAccessoryView:toolbar];
Run Code Online (Sandbox Code Playgroud)
和-resignKeyboard看起来像:
-(void)resignKeyboard {
[aTextField resignFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助别人.
amr*_*rox 24
如果您注册键盘通知,即UIKeyboardWillShowNotification UIKeyboardWillHideNotification等,您收到的通知将包含userInfodict(UIKeyboardBoundsUserInfoKey)中键盘的边界.
请参阅UIWindow课程参考.
Dav*_*eck 16
在3.0及更高版本中,您可以从userInfo通知字典中获取动画持续时间和曲线.
例如,要为视图的大小设置动画以为键盘腾出空间,请注册UIKeyboardWillShowNotification并执行以下操作:
- (void)keyboardWillShow:(NSNotification *)notification
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
[UIView setAnimationDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
CGRect frame = self.view.frame;
frame.size.height -= [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size.height;
self.view.frame = frame;
[UIView commitAnimations];
}
Run Code Online (Sandbox Code Playgroud)
做一个类似的动画UIKeyboardWillHideNotification.