Multiple Inheritance Required in Objective-C

I want to implement a movable UIView class (the view moves when you touch it and move your finger), for example:

@interface MovableView : UIView {
  some members;
 }
-touchesBegan;
-touchesMoved;
@end

How can I apply this code to UILabel, UIButton, etc. without multiple inheritance? In C ++, I would do it like this (with UIView as a virtual base for MovableView):

struct MovableLabel : UILabel, MovableView {};

Categories are offered as an alternative to multiple inheritance, but I definitely don't want to distribute UIView using categories, because this applies to all views in my application. I want some of my views to be mobile.

My current strategy for avoiding code duplication is to put MovableView code in the header file and include it every time I need some class to use it. In addition, I have to add MovableView members to any class I write. This is pure code ugliness, but better than copying / pasting code throughout my project.

Does anyone have any other ideas around this Objective-C restriction [not to have multiple inheritance]?

Thank,

Altan

+3
source share
2 answers

Objective-C mixin, , . .

, MovableView , , (UILabel, UIButton ..), .

+7

, touchBegan UIButton ... [super] .

- :

Method origMethod = class_getClassMethod([UIButton class], @selector(touchesBegan));
Method newMethod = class_getClassMethod([TemplateClass class], @selector(replacementTouchesBegan));
method_exchangeImplementations(origMethod, newMethod);

. , , , ...

, MovableView, UIView, , , , (, , , quixoto, , ). , ... . IB .

UIKit, .

+2

Source: https://habr.com/ru/post/1755612/


All Articles