我目前正在开展一个项目。它可能在多个控制器中具有重复代码,如下所示。
控制器A
class A: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
// about 50~70 lines of codes
@IBAction func scanButtonTapped {
// used self (as AVCaptureMetadataOutputObjectsDelegate)
// used view
// called presentViewController(...), which is a func in UIViewController
}
}
控制器B
class B: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
@IBAction func scanButtonTapped {
// will need same logic as in Controller A
}
}
我当前的解决方案是另一个C类,并将重复的代码移入其中。但是,如果我这样做,控制器可以转换为AVCaptureMetadataOutputObjectsDelegate
,但不转换为UIViewController
。
class C {
func btnTapped (view: UIView, controller: AnyClass) {
// logic is here
// controller can cast to AVCaptureMetadataOutputObjectsDelegate
// but controller cannot cast to UIViewController
}
}
所以A和B将有
class A {
@IBAction func scanButtonTapped {
let c = C()
c.btnTapped(view, self)
}
}
我的问题是,是否可以将控制器转换为UIViewController
。还有另一种方法可以正确地重构代码吗?
答案 0 :(得分:3)
扩展AVCaptureMetadataOutputObjectsDelegate协议并通过协议扩展(POP方法)创建默认实现怎么样?
protocol ScanButtonClickable: AVCaptureMetadataOutputObjectsDelegate {
func btnTapped() // this line is optional
}
extension Clickable where Self: UIViewController {
func btnTapped() {
// logic is here
}
}
class A: UIViewController, ButtonClickable {
...
}
class B: UIViewController, ButtonClickable {
...
}
答案 1 :(得分:0)
试试这个:
//declare your default method to be used across classes
protocol MyProtocol {
func myFunc()
}
//provide the implementation of your default behavior here in myFunc()
extension MyProtocol {
func myFunc() {
print("Default behavior")
}
}
class A: MyProtocol {
}
class B: MyProtocol {
}
let a = A()
a.myFunc()
let b = B()
b.myFunc()
//prints
Default behavior
Default behavior