Reputation: 79
Im a beginner programmer with Xcode 5 and was attempting to write code to allow a user to move a image with input from the users touch.
So far, I believe that my code is correct but i believe I'm missing something as the UIImage refuses move. Although when attempt to test it with NSLog I don't get a response which shows it working. My guess it that I have to make a custom class for the image and if so would I do this and how would I link it.
For example
@implementation StartPage
- (IBAction)HandlePan:(UIGestureRecognizer *)sender; {
NSLog(@"panning"); //Testing to check if the image moves when touched by user.
CGPoint NetTranslation ;
CGPoint Translation =
[(UIPanGestureRecognizer *) sender translationInView: _Imageview ];
sender.view.transform=CGAffineTransformMakeTranslation (
NetTranslation.x += Translation.x,
NetTranslation.y += Translation.y);
enter code here
if(sender.state == UIGestureRecognizerStateEnded)
{
NetTranslation.x += Translation.x;
NetTranslation.y += Translation.y;
}
}
Upvotes: 1
Views: 3066
Reputation: 13294
For swift language we can do like this:
Take a view and set IBOutlet:
@IBOutlet weak var viewDrag: UIView!
var panGesture = UIPanGestureRecognizer()
Write this pretty code on viewDidLoad()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.draggedView(_:)))
viewDrag.isUserInteractionEnabled = true
viewDrag.addGestureRecognizer(panGesture)
This is method which is calling while gesture recognized
@objc func draggedView(_ sender:UIPanGestureRecognizer){
self.view.bringSubviewToFront(viewDrag)
let translation = sender.translation(in: self.view)
viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: self.view)
}
100% working and tested
Upvotes: 0
Reputation: 476
While using any Gesture you should use following steps,
Now you are using pan gesture so i am giving following steps to add pan gesture,
Add delegate like to your header file [ .h file ]
@interface ViewName : UIView <UIGestureRecognizerDelegate>
Declare that gesture
@property (nonatomic,strong) UIPanGestureRecognizer *pan;
Allocate that gesture
pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
Mention where these delegate methods are present
pan.delegate = self;
Adding that gesture to the view like
[self.view addGestureRecognizer:pan];
Defining the handlePan method like as
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
// code for pan gesture here
}
I think you missed to do something... Hope this will solve your problem, check whether you added UIGestureRecognizer in header file or not...
Upvotes: 4
Reputation: 17053
If your HandlePan
method is not called check that your _Imageview has user interactions enabled:
_Imageview.userInteractionEnabled = YES
Upvotes: 1