Reputation: 1179
I tried to use protocol, but it needs to implement "makeMeDraggable" method for each 2 classes with the same content. I wish not to implement in each 2 classes and inherit implementation from Shared Class. How do I achieve it?
Code:
//--(.h)--//
@interface SharedClass : UIView;
-(void) makeMeDraggable
@end
@interface DraggableUITextView: UITextView
@end
@interface DraggableUIImageView : UIImageView
@end
@implementaion SharedClass
-(void) makeMeDraggable {
//some code
}
@end
@implementation DraggableUITextView
@end
@implementation DraggableUIImageView
@end
//--(.m)--//
TextView *textView = [DraggableUITextView initWithFrame:CGRectMake(0,0,50,50)];
[textView makeMeDraggable];
ImageView *imageView = [DraggableUIImageView imageNamed:@"foo.png"];
[imageView makeMeDraggable];
I want to avoid below:
@interface DraggableTextView: UITextView;
-(void) makeMeDraggable
@end
@interface DraggableUIImageView : UIImageView
-(void) makeMeDraggable
@end
@implementation DraggableUITextView
-(void) makeMeDraggable {
//same code...
}
@end
@implementation DraggableUIImageView
-(void) makeMeDraggable {
//same code...
}
@end
Upvotes: 2
Views: 99
Reputation: 1544
Make a UIView
category and write the function there rather than SharedView
.Like:
@interface UIView (UIViewCategory)
-(void) makeMeDraggable;
@end
@implementaion UIView (UIViewCategory)
-(void) makeMeDraggable {
//some code
}
@end
Now you can use makeMeDraggable
method with every object inherited from UIView
class.
Upvotes: 4
Reputation: 9902
The way to do this is with a Category on a common superclass, in your case, UIView
.
The Category extends its class with new methods, which are then available like ordinary methods to all subclasses.
Upvotes: 1
Reputation: 6279
Create a category over UIView with the method makeMeDraggable and you will be able to use it on both UITextView and UIImageView objects.
Upvotes: 1