The right technique for writing reusable interface objects?

I am looking for the right way to create my own interface objects.

Say I want an image that can be double tap.

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
}
// detect tapCount == 2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

This works great - the button accepts events and can detect double branches.

My question is how to handle actions correctly. The two approaches I tried add references to the parent and delegation.

Passing a reference to the parent is pretty simple ...

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
    MainViewController *parentView; // added
}

@property (nonatomic,retain) MainViewController *parentView; // added

// parentView would be assigned during init...
- (id)initWithFrame:(CGRect)frame 
     ViewController:(MainViewController *)aController;

- (id)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

But that would prevent my DoubleTapButtonView class from being easily added to other views and view controllers.

Delegation adds some extra abstraction to the code, but allows me to use DoubleTapButtonView in any class that matches the delegate interface.

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
  id <DoubleTapViewDelegate> delegate;
}

@property (nonatomic,assign) id <DoubleTapViewDelegate> delegate;

@protocol DoubleTapViewDelegate <NSObject>

@required
- (void)doubleTapReceived:(DoubleTapView *)target;

. , , , , .

, ? , UIButton UIController addTarget: . ?

: NSNotificationCenter , .

// listen for the event in the parent object (viewController, etc)
[[NSNotificationCenter defaultCenter] 
  addObserver:self selector:@selector(DoubleTapped:) 
  name:@"DoubleTapNotification" object:nil];

// in DoubleTapButton, fire off a notification...
[[NSNotificationCenter defaultCenter] 
  postNotificationName:@"DoubleTapNotification" object:self];

? , ? ( , ?)

+3
2

.

+2

UIControl -sendActionsForControlEvents:. ... , , , , .

+1

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


All Articles