我目前正在處理一個項目。它可能會在下面的多個控制器中有重複的代碼。控制器中的重複代碼
控制器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
。還有另一種方法來正確地重構代碼嗎?
你爲什麼不這樣做'類C:的UIViewController,AVCaptureMetadataOutputObjectsDelegate {...}'然後'A級:C {'和'B類:C {' ? – luk2302