【发布时间】:2019-12-26 12:16:33
【问题描述】:
我想为 UIViewCntroller 和 UIView 实现自己的 HUD,所以我这样做了:
protocol ViewHudProtocol {
func showLoadingView()
func hideLoadingView()
}
extension ViewHudProtocol where Self: UIView {
func showLoadingView() { //Show HUD by adding a custom UIView to self.}
}
func hideLoadingView() {
}
}
现在我可以轻松地在任何 UIView 上采用 ViewHudProtocol 来调用 showLoadingView 和 hideLoadingView。问题是我想为 UIViewController 使用相同的协议,所以我这样做了:
extension ViewHudProtocol where Self: UIViewController {
func showLoadingView() {
self.view.showLoadingView() //Error: UIView has no member showLoadingView
}
func hideLoadingView() {
self.view.hideLoadingView() //Error: UIView has no member hideLoadingView
}
}
我同意 UIView 尚未采用协议的错误。所以我这样做了:
extension UIView: ViewHudProtocol {}
而且它有效。有一个更好的方法吗?我的意思是用ViewHudProtocol 扩展每个视图感觉不对,因为并非所有人都会使用它。如果我可以做类似的事情,“如果 UIViewController 需要它,则只为 UIView 隐式采用 ViewHudProtocol。否则,您可以在需要时在任何 UIView 上手动采用 ViewHUDProtocol。”
【问题讨论】:
标签: swift protocols swift-protocols