Question

I have a ViewController iDragHomeViewController

and another

NSObject class iDrag

"iDragHomeViewController.m"

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *dragView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    [dragView setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:dragView];

    iDrag *drag = [[iDrag alloc]init];
    [drag makeDraggableView:dragView];
}

"iDrag.m"

-(void)makeDraggableView: (UIView *)dragView {

    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(cellPan:)];
    [dragView addGestureRecognizer:panRecognizer]; 

}

- (void)cellPan:(UIPanGestureRecognizer *)iRecognizer {

   UIView *viewToDrag = [[UIView alloc]init];
   viewToDrag = iRecognizer.view;

   CGPoint translation = [iRecognizer translationInView:[viewToDrag superview]];
   viewToDrag.center = CGPointMake(iRecognizer.view.center.x + translation.x,
                                         iRecognizer.view.center.y + translation.y);
   [iRecognizer setTranslation:CGPointMake(0, 0) inView:[viewToDrag superview]];
}

Now what I am trying here is to make this "dragView"(belongs to iDragHomeViewController) draggable in iDrag class by applying it PanGesture. But the code is crashing.

I know some people will suggest me to use NSNotification to handle Pan action in another class but I dont want to write a single line in iDragHomeViewController and handle everything in iDrag Class only.

Is it Possible ??

Please Help.

Was it helpful?

Solution

To be sure I need to know the error output but a guess...

From UIGestureRecognizer doc:

- (id)initWithTarget:(id)target action:(SEL)action
target parameter:
An object that is the recipient of action messages sent by the receiver when it recognizes a gesture. nil is not a valid value.

Thats the reason why your app crashes. The drag object is already released while the recognizer tries to call the cellPan: method.

You initialize the iDrag object in viewDidLoad and is not retained. (It is not a member variable and not used anywhere else....). End of the viewDidLoad the iDrag object is released by ARC.

I would not make any other object responsible for handling pan gestures, unless I had a good reason for that. And would make the view controller responsible for creating gesture recognizer and handling the events.

I assume you have really good reason for that, like the handling is used by multiple views, etc... If it is the case then a better approach would be making iDrag object singleton(shared instance).

OTHER TIPS

Got the answer

Just need to declare iDrag object as a property

@property(nonatomic,strong) iDrag *drag;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top