【发布时间】:2016-10-31 00:38:10
【问题描述】:
我正在努力使我的代码更有条理和可重用。我有一些功能和通知,允许在键盘显示时向上移动滚动视图并在键盘隐藏时向下滚动。这一切都在运作。但是,我会想象这些功能将用于我的项目的多个部分,这些部分在 UIViewcontroller 中有滚动视图。所以我想创建一个更可重复使用的代码,而不是在多个视图控制器中编写相同的代码。
目前,在我的一个视图控制器中,我有
var keyboard = CGRect()
override func viewDidLoad() {
// Check notifications of keyboard activity
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PostVC.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PostVC.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
// Tap to hide keyboard
let hideTap = UITapGestureRecognizer(target: self, action: #selector(PostVC.hideKeyboard))
hideTap.numberOfTapsRequired = 1
self.view.userInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
}
func hideKeyboard() {
self.view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification) {
keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue())!
UIView.animateWithDuration(0.4) {
self.scrollView.contentSize.height = self.view.frame.size.height + self.keyboard.height / 2 + UITabBarController().tabBar.frame.size.height
}
}
func keyboardWillHide(notification: NSNotification) {
UIView.animateWithDuration(0.4) {
self.scrollView.contentSize.height = 0
}
}
我对尝试使代码更可重用有点陌生。我不确定是否需要创建一个新类或只是创建 UIViewcontroller 的扩展并将其放入其中。我尝试创建 UIViewcontroller 的扩展并执行类似的操作
func keyboardWillShow(notification: NSNotification, _scrollView: UIScrollView) { }
并将滚动视图的实例 (@IBOutlet weak var scrollView: UIScrollView!) 传递给函数。但是,我在做#selector(keyboardWillShow(_:, keyboard: keyboard, scrollView: scrollView) 时遇到了麻烦。它给了我一个错误,说表达式列表中的预期表达式(我认为它在抱怨_:)。我可能走在一条完全错误的道路上。任何人都可以请帮助。
谢谢,
【问题讨论】:
-
如果代码可以在应用程序的许多地方重用,最好为共享代码的所有视图控制器创建一个基类。
-
您是否考虑过在
UIScrollView之类的东西上创建 class extensions?
标签: ios iphone xcode swift keyboard