我尝试使用协议,但是它需要为每个具有相同内容的2个类实现“ makeMeDraggable”方法。我不希望在每个2类中都实现,而不要从Shared Class继承实现。我该如何实现?

码:

//--(.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];


我想避免以下情况:

@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

最佳答案

创建一个UIView类别,然后在其中而不是SharedView编写函数。

@interface UIView (UIViewCategory)
-(void) makeMeDraggable;
@end


@implementaion UIView (UIViewCategory)
-(void) makeMeDraggable {
  //some code
}
@end


现在,您可以对从makeMeDraggable类继承的每个对象使用UIView方法。

09-08 03:34