【发布时间】:2017-02-11 03:30:01
【问题描述】:
在 Objective-C 中,我可以继承一个视图控制器,如下所示。
class KeyboardObserverViewController: UIViewController {
var tableView: UITableView?
init() {
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardObserverViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardObserverViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func keyboardDidShow(_ notification: Notification) {
let rect = ((notification as NSNotification).userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
if let tableView = tableView {
let insets = UIEdgeInsetsMake(tableView.contentInset.top, 0, rect.height, 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
}
}
func keyboardWillHide(_ notification: Notification) {
if let tableView = tableView {
let insets = UIEdgeInsetsMake(tableView.contentInset.top, 0, 0, 0)
UIView.animate(withDuration: 0.3, animations: {
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
})
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
并覆盖表视图变量并返回更专业的表视图(即 UITableView 的子类)。然后,我可以在需要时转换表视图变量。在 Swift 中,这有点棘手,如 this post 中所述。
那么你将如何子类化这个视图控制器,以创建一个具有更多特殊性的类,同时避免LSP violation。还是对视图控制器进行子类化(并对其变量进行子类化),太棘手了?
编辑:关于我的帖子可能类似于 this post 的建议 - 我更关注处理代码重复而不是类与结构。
澄清:我专门在 Swift 中寻找一种方法(或最佳实践),它允许我编写此代码一次,并在使用其 CustomTableView 实例的各种视图控制器子类中使用它拥有。
【问题讨论】:
-
类可以在 Swift 中被子类化,就像在 ObjC 中一样。使用结构体,您可以使用协议,然后使用protocol extensions 为所有采用它的类型提供可用的属性和方法。
-
sketchyTech 您愿意提供一个更详细描述此问题的答案吗?
-
sketchyTech 我将编辑我的帖子以突出手头的问题,更清晰一点。你不是唯一一个讨论过这些观点的人。
-
所以您正在寻找一种面向协议的方式来添加观察者和处理回调?或者它与 UITableView 有什么关系?请澄清
-
你说“[在 Objective-C 中] 我可以在我需要的时候转换表格视图变量”。如果您愿意强制转换访问,您可以在 Swift 中执行相同的操作:
if let specialTable = self.table as? TableSubclass {,并且您根本不需要覆盖该属性。这是你想要避免的吗?
标签: ios swift inheritance