Ios 为所有视图控制器编写一个通用方法,以便在键盘出现时调整内容视图(UIScrollView)的框架
在我的iOS应用程序中,几乎有10个ViewController,其中包含UITextFields。 我实现了当键盘出现时向上移动内容视图的功能 这个网站解释了所有的问题 但我的问题是,我必须在每个视图控制器中重复相同的代码。是他们的任何方式,以便我可以编写通用类或方法,与我所有的10个ViewController一起工作。这样就可以实现代码的可重用性 谢谢你的帮助。提前谢谢 更新: 从apple文档中,我必须使用以下方法。但我一直停留在一个地方,我必须将scrollview实例和活动文本字段(对于每个视图控制器,这些实例是不同的)传递给我的公共类/方法Ios 为所有视图控制器编写一个通用方法,以便在键盘出现时调整内容视图(UIScrollView)的框架,ios,objective-c,Ios,Objective C,在我的iOS应用程序中,几乎有10个ViewController,其中包含UITextFields。 我实现了当键盘出现时向上移动内容视图的功能 这个网站解释了所有的问题 但我的问题是,我必须在每个视图控制器中重复相同的代码。是他们的任何方式,以便我可以编写通用类或方法,与我所有的10个ViewController一起工作。这样就可以实现代码的可重用性 谢谢你的帮助。提前谢谢 更新: 从apple文档中,我必须使用以下方法。但我一直停留在一个地方,我必须将scrollview实例和活动文本字段
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
在scrollView的基本视图控制器中创建属性,并在每个派生视图控制器的viewDidLoad方法中初始化它。同时将activeField属性移动到基本视图控制器。在一个类中创建一个方法,该类必须管理通知scrollview内容,并在appdelagate.m文件[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyboardWasShow:)name:UIKeyboardDidShowNotification对象:nil]; [[NSNotificationCenter defaultCenter]添加观察者:自选择器:@selector(keyboardWillBeHidden:)名称:UIKeyboardWillHideNotification对象:nil];写这2个方法。你可以创建一个子类。。。。然后编写其中常见的任何行为。创建一个所有ViewController都将遵循的基类?您可以使用像或这样的库,应该更多easier@Himanshu莫拉迪亚-你能在回答部分发布更多细节吗?但我如何发送放置在每个视图控制器中的滚动视图实例