給一個可拖拽的對象寫了類。
在快完成的時候想要用delegates使用block,運行正常,不知道能不能在使用@protocol
時有類似 @optional設置?如果不調用myObject.didEndPanning
,應用就會崩潰。
// MyClass.h
#import <Foundation/Foundation.h>
typedef void (^DelegateBlock)(void);
@interface AHDraggableObject : UIView
- (id)initDragableView:(UIView *)view inView:(UIView *)parentView withBorderOffset:(int)offset;
@property (nonatomic, strong) UIView *holder;
@property (nonatomic, weak) DelegateBlock didEndPanning;
@end
// MyClass.m
- (void)handlePanning:(UIPanGestureRecognizer *)sender
{
CGPoint translation = [sender translationInView:_parentView];
sender.view.center = CGPointMake(sender.view.center.x + translation.x, sender.view.center.y + translation.y);
[sender setTranslation:CGPointMake(0, 0) inView:_parentView];
[self checkBondaries:sender withOffset:_offset inView:_parentView];
// end of pan - invoke event
if (sender.state == UIGestureRecognizerStateEnded)
{
_didEndPanning();
}
}
調用
//ViewController.m
-(void)viewDidLoad {
_drag = [[MRShape alloc] initDragableView:_testImageView inView:self.view withBorderOffset:40];
_drag.didEndPanning = ^
{
// if didEndPanning call is missing, app crash !
};
}
檢測block是否設置:
if (sender.state == UIGestureRecognizerStateEnded && _didEndPanning)
{
_didEndPanning();
}