2

I want to implement the approach used by UITableView.

I have subclass UITableView with my own class FloatingTableView I want to override the delegate of UITableView which is UITableViewDelegate with my delegate of type FloatingTableViewDelegate just the way UITableView inherit from UIScrollView and override the UIScrollViewDelegate with UITableViewDelegate both class have same property with name delegate but have different types.

I have also tried to inherit my protocol with UITableViewDelegate But when i try to create property with name delegate of type FloatingTableViewDelegate I get this error..

Property 'delegate' with type 'MyTableViewDelegate?' cannot override a property with type 'UITableViewDelegate?'

Here is my sample code.

protocol MyTableViewDelegate: UITableViewDelegate {
    func isDemoDelegateMethod()
}

class MyTableView: UITableView {
    weak var delegate: MyTableViewDelegate?
}
Syed Qamar Abbas
  • 3,637
  • 1
  • 28
  • 52

1 Answers1

2

The way it works for Objective C is because of the dynamic nature of the language. You can redeclare the type of super class and instead of synthesizing the property you would make it a dynamic type, which would let you redeclare it.

@protocol MyTableViewDelegate<UITableViewDelegate>

- (void)demoDelegateMethod;

@end


@interface WrapperTableView: UITableView

@property (nonatomic, weak, nullable) id <MyTableViewDelegate> delegate;


@end

@implementation WrapperTableView

@dynamic delegate;

@end

But, I doubt this would be possible with Swift, since, you are changing the type completely. It is because of Swift being strong static language.

Answer Edited

I got your approach. I write above approach in Objective-C and then inherit this class in Swift. So if I have to override SuperClass property with different type I need to create a wrapper class in Objective-C inherit from desired SuperClass and then finally instead of inheriting directly from desired super class I should inherit from the newly created WrapperClass which is written in Objective-C

class MyTableView: WrapperTableView {
    //Now Here the delegate object is of type MyTableViewDelegate
}

This approach is far better then

class MyTableView: UITableView {
   private var myDelegate: MyTableViewDelegate?
   override var delegate: UITableViewDelegate { 
        set{
            myDelegate = newValue
        }
        get{
            return myDelegate
        }

   }
}
Syed Qamar Abbas
  • 3,637
  • 1
  • 28
  • 52
Sandeep
  • 20,908
  • 7
  • 66
  • 106