gpt4 book ai didi

ios - touchesBegan、touchesEnded、touchesMoved 用于移动 UIView

转载 作者:IT王子 更新时间:2023-10-29 08:05:36 24 4
gpt4 key购买 nike

我需要拖动我的 UIView 对象。我使用了这段代码,但它不起作用

float oldX, oldY;
BOOL dragging;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];

if ([[touch.view class] isSubclassOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)touch.view;
if (CGRectContainsPoint(label.frame, touchLocation)) {
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
}
}


}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

dragging = NO;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];

if ([[touch.view class] isSubclassOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)touch.view;

if (dragging) {
CGRect frame = label.frame;
frame.origin.x = label.frame.origin.x + touchLocation.x - oldX;
frame.origin.y = label.frame.origin.y + touchLocation.y - oldY;
label.frame = frame;
}

}


}

最佳答案

我建议使用 UIPanGestureRecognizer:

-(void)dragging:(UIPanGestureRecognizer *)gesture
{
// Check if this is the first touch
if(gesture.state == UIGestureRecognizerStateBegan)
{
// Store the initial touch so when we change positions we do not snap
self.panCoord = [gesture locationInView:gesture.view];
[self.view bringSubviewToFront:gesture.view];

}

CGPoint newCoord = [gesture locationInView:gesture.view];

// Create the frame offsets to use our finger position in the view.
float dX = newCoord.x-self.panCoord.x;
float dY = newCoord.y-self.panCoord.y;

gesture.view.frame = CGRectMake(gesture.view.frame.origin.x+dX,
gesture.view.frame.origin.y+dY,
gesture.view.frame.size.width,
gesture.view.frame.size.height);
}

这只是我的偏好。对我来说,使用手势识别器比使用 touchesBegantouchesEndedtouchesMoved 要简单得多。我将在 UIPanGestureRecognizer 不起作用的情况下使用它们。

关于ios - touchesBegan、touchesEnded、touchesMoved 用于移动 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14856906/

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