【问题标题】:Delegate pattern without storyboard or segue没有故事板或 segue 的委托模式
【发布时间】:2017-06-22 13:06:45
【问题描述】:

我正在学习深入了解委托模式。 iOS中很多代码示例使用了两个ViewControllers,其中涉及prepare(for segue:...)

我希望我的程序仅使用一个带有委托协议的 ViewController,但不使用 segue 或情节提要。 ViewController 有一个按钮来执行一个简单的委托方法,比如说添加一个数字。

ViewController 类:

class ViewController: UIViewController, theDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
}

// It is here I got stuck
// How do I set delegate = self without out involving segue or the     storyboard at all? Do I need to instantizate the dedecated delegate class and how?
// To conform to delegate -- theDelegate
func add(num: Int) {
    // Output result on ViewController
}

func minus(num: Int) {
    // Output result on ViewController
}
}

专用Delegate类:

protocol theDelegate: class {
func add(num: Int)
func minus(num: Int)
}

class ClassDelegate: NSObject {
weak var delegate: theDelegate?

func x() {
    delegate?.add(num: 100)
}
}

【问题讨论】:

    标签: swift delegates viewcontroller


    【解决方案1】:

    如果您的视图控制器是委托,那么您的类命名会令人困惑。你所谓的ClassDelegate 不会是任何类型的委托,而是使用委托的“工人”。不过……

    var worker = ClassDelegate()
    override func viewDidLoad() {
        super.viewDidLoad()
        worker.delegate = self
        worker.x()
    }
    

    【讨论】:

    • 哦,我明白了。我想我是反过来的。所以采用协议的类才是真正的委托类,而我所谓的ClassDelegate只是协议,应该改名为ClassProtocol对吗?抱歉,英语不是我的第一语言。
    • ClassDelegate 仅与协议有关,因为它使用它。确实,没有理由将其称为“委托”或“协议”。考虑一个表格视图;它使用了一个委托,但我们没有以任何与委托协议相关的方式命名它。
    • 我明白了。非常感谢您帮我解决这个问题。 :)
    【解决方案2】:

    @PhillipMills 的回答应该是正确的,只是在thisthis 中添加一些关于命名约定的注释,以便您获得更好的代码质量。

    • 您应该对类型(和协议)使用大写字母,对其他所有内容使用小写字母
    • 不需要从 NSObject 继承,除非你想从 ObjC 世界中获得一些东西,无论是使用 ObjC 还是使用 KVO

    【讨论】:

    • 感谢大家的回复。 @PhillipMills 我不太清楚你的意思,你是说我没有正确使用委托模式吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2012-04-07
    • 2015-12-13
    相关资源
    最近更新 更多