gpt4 book ai didi

ios - 为所有 View Controller 编写一个通用方法,以在出现键盘时调整内容 View (UIScrollView)的框架

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:16 24 4
gpt4 key购买 nike

在我的 iOS 应用程序中,几乎有 10 个 ViewController,其中存在 UITextFields。我实现了在键盘出现时向上移动内容 View 的功能。

https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

这个网站解释了一切。

但我的问题是我必须在每个 View Controller 中重复相同的代码。他们有什么办法让我可以编写适用于我所有 10 个 ViewController 的通用类或方法,从而实现代码的可重用性?

从苹果文档中,我必须使用以下方法。但是我被困在一个地方,我必须将 ScrollView 和事件文本字段的实例(对于每个 View Controller ,这些实例都是不同的)传递给我的通用类/方法。

// 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;
}

最佳答案

在基本 View Controller 中为 scrollView 创建属性,并在每个派生 View Controller 的 viewDidLoad 方法中初始化它。同时将 activeField 属性移动到基本 View Controller 。

关于ios - 为所有 View Controller 编写一个通用方法,以在出现键盘时调整内容 View (UIScrollView)的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com