相当常见的问题,我有几个答案,我几乎就在那里。我有一个按钮,按下后,将创建一个图像(代码如下)
(numImages在加载时设置为ZERO,用作所有图像的标记号的计数)
UIImage *tmpImage = [[UIImage imageNamed:[NSString stringWithFormat:@"%i.png", sender.tag]] retain];
UIImageView *myImage = [[UIImageView alloc] initWithImage:tmpImage];
numImages += 1;
myImage.userInteractionEnabled = YES;
myImage.tag = numImages;
myImage.opaque = YES;
[self.view addSubview:myImage];
[myImage release];
然后我有一个touchesBegan方法,它将检测触摸的内容。我需要它做的是允许用户拖动新创建的图像。它几乎可以正常工作,但拖动它时图像会闪烁不已。我可以访问你点击的图像,因为我可以得到它的标签,但我不能很好地拖动它。
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
if (touch.view.tag > 0) {
touch.view.center = location;
}
NSLog(@"tag=%@", [NSString stringWithFormat:@"%i", touch.view.tag]);
}
- (void) touchesMoved:(NSSet *)touches withEvent: (UIEvent *)event {
[self touchesBegan:touches withEvent:event];
}
它的工作原理是,当我点击它们时,我会得到每个图像的标记输出。但是当我拖动时,它闪烁......任何想法?
答案 0 :(得分:34)
在回答我自己的问题时 - 我决定创建一个类来处理我放在视图上的图像。
代码,如果有人感兴趣....
Draggable.h
#import <Foundation/Foundation.h>
@interface Draggable : UIImageView {
CGPoint startLocation;
}
@end
Draggable.m
#import "Draggable.h"
@implementation Draggable
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
// Move relative to the original touch point
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
@end
并称之为
UIImage *tmpImage = [[UIImage imageNamed:"test.png"] retain];
UIImageView *imageView = [[UIImageView alloc] initWithImage:tmpImage];
CGRect cellRectangle;
cellRectangle = CGRectMake(0,0,tmpImage.size.width ,tmpImage.size.height );
UIImageView *dragger = [[Draggable alloc] initWithFrame:cellRectangle];
[dragger setImage:tmpImage];
[dragger setUserInteractionEnabled:YES];
[self.view addSubview:dragger];
[imageView release];
[tmpImage release];
答案 1 :(得分:1)
通常在更改center
时会获得隐式动画。您是否正在弄乱-contentMode
或任何机会致电-setNeedsDisplay
?
您可以显式请求动画以避免删除并以这种方式重新绘制:
if (touch.view.tag > 0) {
[UIView beginAnimations:@"viewMove" context:touch.view];
touch.view.center = location;
[UIView commitAnimations];
}
请注意NSLog()
可能非常慢(比您预期的要慢得多;它比简单的printf
要复杂得多),这会导致像{{{}}那样频繁出现问题{1}}。
顺便说一下,你正在泄漏touchesMoved:withEvent:
。