gpt4 book ai didi

iphone - UIPanGestureRecognizer 不适用于按钮

转载 作者:行者123 更新时间:2023-11-30 15:56:26 27 4
gpt4 key购买 nike

我遇到了 UIPanGestureRecognizer 的问题。假设我使用不同的标签动态添加 10 个按钮,当我添加第一个按钮时,尝试将其拖动到其他位置,然后它就可以正常工作。然后,如果我添加其他按钮,然后尝试拖动第二个按钮,那么即使它工作正常,但如果我会拖动第一个按钮,那么它就不会被拖动。日志中显示的消息是忽略对 [UIPanGestureRecognizer setTranslation:inView:] 的调用,因为手势识别器未激活。手势仅适用于最近添加的按钮。下面是我正在使用的代码

<小时/>

这是添加按钮的代码

    NSUInteger counter = 1;
if([ButtonArray count] !=0 ){
NSLog(@"%d",[ButtonArray count]);
NSLog(@"hi");
counter = [ButtonArray count] + 1;

}
[ButtonArray addObject:[NSString stringWithFormat:@"%d",counter]];
NSLog(@"%d",1);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTag:counter];
btn.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
//[btn addTarget:self action:@selector(Dragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
//[self.view addSubview:btn];
btn.userInteractionEnabled = YES;

gesture = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:@selector(labelDragged:)];
[btn addGestureRecognizer:gesture];
// add it

[self.view addSubview:btn];

这是手势代码

    UIButton *button = (UIButton *)gesture.view;

CGPoint translation = [gesture translationInView:button];


// move button
button.center = CGPointMake(button.center.x + translation.x,
button.center.y + translation.y);

// reset translation
[gesture setTranslation:CGPointZero inView:button];
<小时/>

最佳答案

我怀疑问题归结为:

gesture = [[UIPanGestureRecognizer alloc] 
initWithTarget:self
action:@selector(labelDragged:)];

我倾向于从你的代码中认为手势是你的类中的一些属性。在这种情况下,当您创建新手势时,您会不断覆盖旧的手势。这也可以解释您所描述的行为。

编辑:

您并不严格需要将手势识别器存储在属性中;这样做就足够了:

UIPanGestureRecognizer* localgesture = [[UIPanGestureRecognizer alloc] 
initWithTarget:self
action:@selector(labelDragged:)];
[btn addGestureRecognizer:localgesture];

然后,当调用 labelDragged 方法时,您可以使用其 recognizer 参数来了解触发了哪些手势识别器:

- (void)labelDragged:(UIGestureRecognizer *)gestureRecognizer;

关于iphone - UIPanGestureRecognizer 不适用于按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11280436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com