在我的应用程序中我有8个文本字段。当键盘出现时我已经实现了scrollview,但是当我开始在第一个文本字段中输入文本时,视图会滚动并隐藏我当前聚焦的文本字段。我希望滚动应该发生在我在某个特定的文本字段中输入文本时,假设从第5个开始。我怎么能这样做。
答案 0 :(得分:1)
使用NSNotifications了解键盘的高度:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboardEditProfile) name:UIKeyboardWillShowNotification object:nil];
然后 实现此功能以获得键盘的高度:
-(void)showKeyBoard:(NSNotification *)notification
{
NSDictionary *info=[notification userInfo];
keyboardSize=[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
}
这将为您提供键盘的大小。
现在使用文本字段的标签按其外观的递增顺序设置,并将视图控制器设置为其委托。
然后使用此委托方法设置scrollView的contentOffset:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}
答案 1 :(得分:1)
嗨我已经使用了很长时间的代码,它对scrollview和tableview非常有用
#pragma mark
#pragma mark - text field delegate method
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[self showKeyBoard:YES];
[self setTableOffsetForTextField:textField];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[self.view endEditing:YES];
[self showKeyBoard:NO];
return YES;
}
#pragma mark - Show Hide Key Board
- (void)showKeyBoard:(BOOL)boolValue
{
scrollView.contentInset = UIEdgeInsetsMake(0, 0, boolValue ? ([self kbHeight1]) : 0.0, 0.0);
}
- (CGFloat)kbHeight1
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
return 264.0;
}
else
{
return 352.0;
}
}
else
{
return 216.0;
}
}
- (void)setTableOffsetForTextField:(UIView *)textField
{
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)){
return;
}
CGPoint point = [textField convertPoint:textField.frame.origin toView:scrollView];
CGFloat diff = [self difference];
CGFloat pos = (point.y - diff);
if (pos < 0 || pos > scrollView.contentSize.height - diff) {
pos = 0;
}
[scrollView setContentOffset:CGPointMake(0, pos) animated:YES];
}
-(CGFloat)difference{
CGSize screenSize = self.view.frame.size;
CGFloat diff;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
diff = (screenSize.height > 768) ? 264.0 : 250;
}
else
{
diff = (screenSize.height == 480) ? 120.0 : 70.0;
}
return diff;
}
这可能对你有所帮助。
答案 2 :(得分:0)
您可以使用标签来完成。
为8个文本字段将标记添加到1-8文本字段。检查文本字段的标记值是否等于或大于5,然后仅应用您的scrollview else return;
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if(textField.tag==5 || textField.tag>=5)
{
//Implement scrollview here
}
}
希望它可以帮助你......!