用触摸移动UIButton

时间:2011-10-27 18:04:29

标签: ios events uiview uibutton touch

我正在使用:

[button addTarget:self action:@selector(moved:) forControlEvents:UIControlEventTouchDragInside];

功能代码移动:

- (IBAction)moved:(id)sender {
UIButton *t = sender;

UITouch *touch = [touch self];

CGPoint touchPoint = [touch locationInView: self];

t.center = touchPoint;
}

所以,当我开始拖动按钮时,它突然出现在左上角(Coord:0; 0)。我认为这是一个问题,因为CGPoint touchPoint = [touch locationInView: self];以错误的方式工作。 我有3个类:viewController,它实现了:

view = [[MainView alloc] initWithFrame:[self.view frame] ];
[self.view addSubview:view];

其中view是类mainview(子类uiview)的对象。在mainview中,我创建类Button(子类uiview)的对象:

[self addSubview:but];

然后在类Button中创建UIButton,与事件UIControlEventTouchDragInside相关联(参见帖子的开头)。

那么我应该如何纠正我的代码,该按钮正确移动到触摸点???

P.S。对不起我糟糕的英语=)

1 个答案:

答案 0 :(得分:2)

如果您真的想坚持使用UIControlEventTouchDragInside,请使用下面的代码段。我个人会改用UIPanGestureRecognizer

- (IBAction)moved:(UIButton *)sender {
    UITouch *touch = [touch self];
    CGPoint touchPoint = [touch locationInView: sender.superview];
    sender.center = touchPoint;
}