我一直试图通过覆盖touchesMoved方法在iOS中实现可拖动的UIButton。 按钮显示,但我无法拖动它。我在这里缺少什么? this is what i reffered
这是我的.h文件。
@interface ButtonAnimationViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *firstButton;
和.m文件。
@implementation ButtonAnimationViewController
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint pointMoved = [touch locationInView:self.view];
self.firstButton.frame = CGRectMake(pointMoved.x, pointMoved.y, 73, 44);
}
答案 0 :(得分:0)
在这里,你有一个完全正常工作的按钮拖动示例使用UIPanGestureRecognizer
,在我看来,这更容易。我在发布代码之前测试了它。如果您还有其他问题,请与我们联系:
@interface TSViewController ()
@property (nonatomic, strong) UIButton *firstButton;
@end
@implementation TSViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// this code is just to create and configure the button
self.firstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.firstButton setTitle:@"Button" forState:UIControlStateNormal];
self.firstButton.frame = CGRectMake(50, 50, 300, 40);
[self.view addSubview:self.firstButton];
// Create the Pan Gesture Recognizer and add it to our button
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragging:)];
[self.firstButton addGestureRecognizer:panGesture];
}
// this method will be called whenever the user wants to drag the button
-(void)dragging:(UIPanGestureRecognizer*)panGesture {
// if is not our button, return
if (panGesture.view != self.firstButton) {
return;
}
// if the gesture was 'recognized'...
if (panGesture.state == UIGestureRecognizerStateBegan || panGesture.state == UIGestureRecognizerStateChanged) {
// get the change (delta)
CGPoint delta = [panGesture translationInView:self.view];
CGPoint center = self.firstButton.center;
center.x += delta.x;
center.y += delta.y;
// and move the button
self.firstButton.center = center;
[panGesture setTranslation:CGPointZero inView:self.view];
}
}
@end
希望它有所帮助!