我有一个应用程序,你必须用触摸移动不同的字母(以UILabels
的形式)。由于有许多不同的UILabel
对象,我尝试创建此代码,以防止任何标签粘在一起:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView: self.view];
bool pickup = YES;
if (pickup) {
if (CGRectContainsPoint(a.frame, touchPoint)) {
a.center = touchPoint;
pickup = NO;
}
}
if (pickup) {
if (CGRectContainsPoint(x.frame, touchPoint)) {
x.center = touchPoint;
pickup = NO;
}
}
if (pickup) {
if (CGRectContainsPoint(x2.frame, touchPoint)) {
x2.center = touchPoint;
pickup = NO;
}
}
if (pickup) {
if (CGRectContainsPoint(eq.frame, touchPoint)) {
eq.center = touchPoint;
pickup = NO;
}
}
if (pickup) {
if (CGRectContainsPoint(b.frame, touchPoint)) {
b.center = touchPoint;
pickup = NO;
}
}
}
但是这里有一些问题:
移动不平滑,标签在我的手指移动图像后停止移动(显然是因为if (CGRectContainsPoint(a.frame, touchPoint))
此外,一旦我在移动另一个标签时绕过标签,我的手指开始移动标签我绕过
我怎么能这样做,我知道现在正在做的事情有更好的方法......
答案 0 :(得分:2)
尝试将其全部放在一个链式动画中touchesMoved
是旧学校。在每个标签上添加手势识别器。然后在那个选择器中尝试这个 -
- (void)labelTouchSelector:(UIGestureRecognizer *)gesture
{
CGPoint touchPoint = [gesture locationInView: self.view];
[UIView animateWithDuration:1.0
delay:0
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
animations:^(void)
{
if(CGRectContainsPoint(a.frame, touchPoint))
{
a.center = touchPoint;
pickup = NO;
}
}
completion:^(BOOL finished)
{
if(finished)
{
//do some cleanup here
pickup = NO;
}
}];
return;
}
答案 1 :(得分:0)
我会尝试创建一个新的UILabel类,它将实现touchesBegan,touchesMoved和touchesEnded。将相关代码放在每个方法中。为此类创建一个方法,为成员分配字母的值。在ViewController中实例化此类的每个新对象,并在此处设置其字母以及其他必要的详细信息,例如label.center。我希望这会有所帮助。
我的代码示例(使用UIImage,你需要找到一种用UILabel初始化类的方法,但标准方法是这样做的):
@implementation myClass
- (id)initWithImage:(UIImage *)image
{
if (self = [super initWithImage:image])
self.userInteractionEnabled = YES;
return self;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
pos = [touch locationInView: self];
self.center = pos;
NSLog(@"Touches Began Called.");
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
activePoint = [[touches anyObject] locationInView:self];
int dx = self.center.x + (activePoint.x - pos.x);
int dy = self.center.y + (activePoint.y - pos.y);
CGPoint newPoint = CGPointMake(dx,dy);
self.center = newPoint;
NSLog(@"Touches Moved Called.");
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"Touches Ended Called.");
}