8

これはかなり一般的な質問ですが、いくつかの答えがあり、ほぼそこにいます。押すと画像が作成されるボタンがあります(次のコード)

(numImages はロード時にゼロに設定され、作成されたすべてのイメージのタグ番号のカウントアップとして使用されます)

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

画像をクリックすると、各画像のタグの出力が得られるという点で機能します。しかし、ドラッグすると点滅します...何かアイデアはありますか?

4

2 に答える 2

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];
于 2010-01-02T19:42:47.823 に答える
1

通常、変更すると暗黙的なアニメーションが表示されますcenter。ひょっとしていじっ-contentModeたり電話したり-setNeedsDisplayしていませんか?

この方法で削除と再描画を回避するためにアニメーションを明示的に要求できます。

if (touch.view.tag > 0) {
    [UIView beginAnimations:@"viewMove" context:touch.view];
    touch.view.center = location;
    [UIView commitAnimations];
}

は非常に遅くなる可能性があることに注意してくださいNSLog()(予想よりもはるかに遅くなります。単純な よりもはるかに複雑ですprintf) touchesMoved:withEvent:

ところで、あなたは漏れていますtmpImage

于 2010-01-02T16:48:10.060 に答える