ios - 子类中是否有符合自定义协议(protocol)的常规空白函数?

标签 ios swift xcode subclass swift-protocols

我的应用程序中有两个主屏幕,目前两者都只是 UIViewController 的子类。这两个 View Controller 非常相似 - 它们都实现了我的自定义子类 UIView ,称为 HeaderView ,负责显示信息和接受用户输入。就目前而言,此代码是重复的,因为两个 View Controller 的 HeaderView 设置相同 - 唯一的区别是当用户确认 HeaderView 中的文本输入时会发生什么。

为了减少重复代码,我创建了一个名为 InputViewController 的类(UIViewController 的子类),它包含两个 View Controller 相同的方面。最终,我希望这两个 View Controller 子类化 InputViewController 而不是 UIViewController

class InputViewController: UIViewController, InputProtocol {

    private let headerView = HeaderView()
        
    override func viewDidLoad() {
        super.viewDidLoad()
        // layout, etc.
        setupCallbacks()
    }
    
    internal func setupCallbacks() {
        headerView.onUpdate = { (text: String) in
            // called when user confirms text entry in headerView
            self.onHeaderUpdate()
        }
    }
    
    internal func onHeaderUpdate() {} // Blank function
    
}

setupCallbacks()onHeaderUpdate() 是在 InputViewController 遵循的协议(protocol)中定义的方法。 HeaderView 实现了一个回调闭包,该回调闭包由 headerView.onUpdate...

setupCallbacks() 中处理

InputViewController遵循的协议(protocol):

protocol InputProtocol {
    func setupCallbacks()
    func onHeaderUpdate()
}

为了说明这一点,我画了一个图表; diagram

由于我希望InputViewController的子类重写onHeaderUpdate()方法,所以传统上是保留onHeaderUpdate()的定义吗在 InputViewController 中为空还是有其他解决方案?

最佳答案

is it conventional to leave the definition of onHeaderUpdate() in InputViewController blank

是的,这被称为抽象方法。通常会给它故意崩溃的代码,以此表达“我的存在只是为了在子类中被重写。” p>

(我应该进一步说,您正在创建的基础 View Controller 执行所有子类必须实现的初始配置,也是正常的。)

关于ios - 子类中是否有符合自定义协议(protocol)的常规空白函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63831683/

相关文章:

ios - 在 FireBase Swift 中从 '[[String : Any]]' 转换为不相关类型 '[String : Any]' 总是失败

iphone - 如何在通过 Storyboard添加的 UINavigationController 中设置 UINavigationItem 的颜色?

ios - 使用 swift 在 UITableView 中添加 UIButton(跟随按钮)

iphone - 善用 XCode 性能工具

xcode - 将框架与 XCode 中的应用程序捆绑在一起

c - Xcode 中的访问错误

ios - 如何获取已存在共享的 CKShare 对象(以获取共享 URL)

iphone - UIPageViewController 代码中的部分 curl

ios - 返回所选项目时选项卡栏不可见

ios - 错误 "Missing argument for parameter ' 编码器在通话中”