例如,我有这5个名称为OneTVC, TwoTVC, ..., FiveTVC
的TVC,并且所有已实施名为SomeProtocol
的协议
protocol SomeProtocol {
var sourceViewController: UIViewController! { get set }
weak var bottomView: SomeCustomView! { get set }
func configure(sourceViewController sourceViewController: UIViewController)
}
所有TVC都使用相同的代码实现了SomeProtocol
class OneTVC: UITableViewCell, SomeProtocol {
var sourceViewController:UIViewController!
@IBOutlet weak var bottomView: SomeCustomView!
func configure(sourceViewController sourceViewController: UIViewController) {
self.sourceViewController = sourceViewController
bottomView.btnOne.addTarget(.... #selector(self.doSomething(_:)))
bottomView.addTarget(.... #selector(self.doAnother(_:)))
}
}
/* all these codes */
extension OneTVC {
func doSomething(sender:UIButton) {
// same codes as TwoTVC ..., FiveTVC
}
func doAnother(sender:UIButton) {
// same codes as TwoTVC ..., FiveTVC
}
}
/* all these codes */
我希望能做的不是写在/* all these codes */
使用协议我可能会做这样的事情
protocol SomeProtocol {
var sourceViewController: UIViewController! { get set }
weak var bottomView: SomeCustomView! { get set }
func configure(sourceViewController sourceViewController: UIViewController)
}
extension SomeProtocol {
func doSomething(sender:UIButton) {
// some custom implementation
}
func doAnother(sender:UIButton) {
// some custom implementation
}
}
但我无法做到这一点,因为@objc protocol SomeProtocol
需要将此协议声明为像addTarget(_:, _:, _:)
这样的Objective-C协议,但通过这样做,我无法使用这些可选或隐式运算符! or ?
用于在协议中声明变量
如果我创建一个超类,我不能覆盖我需要的@IBOutlets变量。
class SomeSuperClass: UITableViewCell, SomeProtocol {
var sourceViewController:UIViewController!
@IBOutlet weak var bottomView: SomeCustomView!
func configure(sourceViewController sourceViewController: UIViewController) {
self.sourceViewController = sourceViewController
bottomView.btnOne.addTarget(.... #selector(self.doSomething(_:)))
bottomView.addTarget(.... #selector(self.doAnother(_:)))
}
}
class OneTVC: SomeSuperClass {
@IBOutlet override weak var bottomView: SomeCustomView! // < this here makes an error
// .. rest of the codes
}
我该怎么办?