gpt4 book ai didi

swift - Swift 中的通用 MVP 实现

转载 作者:行者123 更新时间:2023-11-28 15:09:14 28 4
gpt4 key购买 nike

这个想法是用基本协议(protocol)和类来实现 MVP 结构,这些协议(protocol)和类持有对通用 View 和呈现器的引用

// --- Base --- //
protocol BaseViewProtocol: class {
associatedtype P: BasePresenterProtocol
var presenter: P? { get set }
}
class BaseView<P: BasePresenterProtocol>: UIView, BaseViewProtocol {
var presenter: P?
}

protocol BasePresenterProtocol {
associatedtype V: BaseViewProtocol
weak var view: V? { get set }
}
class BasePresenter<V: BaseViewProtocol>: BasePresenterProtocol {
weak var view: V?
}

// --- Current --- //
protocol CurrentViewProtocol: BaseViewProtocol {
}
class CurrentView<P: CurrentPresenterProtocol>: BaseView<P>, CurrentViewProtocol {
}

protocol CurrentPresenterProtocol: BasePresenterProtocol {
}
class CurrentPresenter<V: CurrentViewProtocol>: BasePresenter<V>, CurrentPresenterProtocol {
init(currentView: V) {
super.init()
self.view = currentView
}
}

问题是如何实例化所有这些类的具体实现,因为View和Presenter都是通用类并且相互依赖

最佳答案

不确定这是最好的方式,但我用这种方式做过类似的事情

  protocol Presentable {
associatedtype View: ViewAble
weak var view: View? {get set}

init(with view: View)

func onAttach(view: View)
func onDetach()

var isAttached: Bool {get}
}

extension Presentable {
var isAttached: Bool {
return view != nil
}
}



class Presenter: Presentable {

weak var view: ViewAble? {
didSet {
if let view = view {
onAttach(view: view)
} else {
onDetach()
}
}
}


required init(with view: ViewAble) {
self.view = view
}

func onAttach(view: View) {
//pre set up on construction

}
func onDetach() {
//release some resource on destroying view
}
}




@objc protocol ViewAble: class {
@objc optional func showError(_ message: String, _ callBack: (() -> Void)?)
}

extension ViewAble where Self: UIViewController {
func showAlert(_ message: String?, _ callBack: (() -> Void)? = nil) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default) { action in
callBack?()
})
self.present(alertController, animated: true, completion: callBack)
}

func showLoading() {
//show default Loading here and override if want custom

}
func stopLoading() {
//stop default Loading
}
}

class ViewController: ViewAble {

}

关于swift - Swift 中的通用 MVP 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47938477/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com