【问题标题】:Use UIViewController class on UITableViewController在 UITableViewController 上使用 UIViewController 类
【发布时间】:2016-03-14 20:30:32
【问题描述】:

我有一个继承自 UIViewController 的 Swift 类,我想知道是否有任何方法可以在 UITableViewController 上使用相同的类来避免重复。

class GradientViewController: UIViewController {
    // My class
}

有没有办法像这样在 UITableViewController 上使用这个类?

class MyTableViewController: GradientViewController {
    // My table view controller
}

提前致谢

【问题讨论】:

    标签: ios iphone swift uiviewcontroller uikit


    【解决方案1】:

    Swift 只支持单继承。

    您可以使用协议来避免重复。

    protocol YourProtocolName {
        // Protocol stuff
    }
    
    class GradientViewController: UIViewController, YourProtocolName {
        // Implement protocol requirements
    }
    
    class MyTableViewController: UITableViewController, YourProtocolName {
        // Implement protocol requirements
    }
    

    如果有意义,您甚至可以使用协议扩展来提供默认实现,以便符合类型不需要添加任何代码来符合。

    【讨论】:

    • 有什么方法可以使用这个(self.view.addSubview)引用控制器的 UIView,或者覆盖 viewWillTransitionToSize 之类的方法?
    • 你是在问是否可以在协议扩展中做这些事情?
    • 我通过在协议中添加一个变量 UIView 并在扩展的方法中使用它来解决这个问题。我现在收到一个我不符合协议的错误。如何确保协议使用我在扩展中添加的默认实现?
    • 当我看不到你在做什么时,我很难提供帮助。可以分享一下代码吗?
    • 我解决了这个问题。现在我有了一个新的,我无法从我的方法中更改变量的值。我在这里发布了代码:pastebin.com/bsyQtscs。可以通过查找“问题:我需要能够更改变量属性”来找到问题。感谢您的帮助
    猜你喜欢
    • 2014-02-07
    • 1970-01-01
    • 2013-12-29
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多