通过触摸移动 UIButton

发布于 2024-12-12 01:32:55 字数 871 浏览 0 评论 0原文

我正在使用:

[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;
}

所以,当我开始拖动按钮时,它突然出现在左上角(坐标: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 关联(参见帖子开头)。

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

PS 抱歉我的英语很糟糕=)

I'm using :

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

Function code move:

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

UITouch *touch = [touch self];

CGPoint touchPoint = [touch locationInView: self];

t.center = touchPoint;
}

So, when I start to drag the button, it suddenly appears in left up corner (Coord: 0;0). I thought this was a problem because CGPoint touchPoint = [touch locationInView: self]; works in wrong way.
I've got 3 classes: viewController, which makes implement of:

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

where view is object of class mainview(subclass uiview). In mainview i make object of class Button(subclass uiview):

[self addSubview:but];

Then in class Button i make UIButton, associating with event UIControlEventTouchDragInside(see beginning of post).

So how should i correct my code, that button move to touch point correctly???

P.S. Sorry for my awful English=)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静若繁花 2024-12-19 01:32:55

如果您确实想坚持使用 UIControlEventTouchDragInside,请使用下面的代码片段。就我个人而言,我会使用 UIPanGestureRecognizer 代替。

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

If you really want to stick with UIControlEventTouchDragInside then use the snippet below. Personally I would use UIPanGestureRecognizer instead.

- (IBAction)moved:(UIButton *)sender {
    UITouch *touch = [touch self];
    CGPoint touchPoint = [touch locationInView: sender.superview];
    sender.center = touchPoint;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文