如何在iOS 6中实现可拖动的UIButton?
我一直在尝试通过覆盖touchesMoved方法在iOS中实现可拖动的UIButton。 按钮出现了,但是我无法拖动它。我在这里遗漏了什么? 这是我的.h文件如何在iOS 6中实现可拖动的UIButton?,ios,uibutton,Ios,Uibutton,我一直在尝试通过覆盖touchesMoved方法在iOS中实现可拖动的UIButton。 按钮出现了,但是我无法拖动它。我在这里遗漏了什么? 这是我的.h文件 @interface ButtonAnimationViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *firstButton; 和.m文件 @implementation ButtonAnimationViewContr
@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);
}
这里有一个使用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
希望有帮助 你能在TouchsMoved中记录你的x和y吗?我试着注销这个位置…结果TouchsMoved方法根本没有执行。这就是我想的,你的ButtonImationViewController是其他控制器的子控制器吗?不…只是普通的UIViewController触摸…代码在UIView中,而不是UIViewController中。您需要在UIButton或UIView子类中处理此问题。平移手势识别器更适合这个用途。比一吨重的路易斯…它就像一个符咒。只是出于好奇,我做错了什么?老实说,我不确定。随着手势识别器的引入,现在我几乎从不使用触摸。。。方法。我想我需要看看你剩下的代码。我很高兴这对你有用,谢谢你接受了答案。。。我想我现在必须研究手势识别器。