Xcodeの:画像(同じ位置)に触れる上の画像を変更するには?
-
19-09-2019 - |
質問
単に、私はUIViewの中にInterface Builderで画像を配置しています。今、私は別の画像をロードする必要があるとき、たとえば、私はその画像をタッチしていメソッド/関数を実行します。
私のコード:
- (void)touchesended:(NSSet*) touches withEvent:(UIEvent *)event
{
// UITouch *touch = [touch anyObject];
bild_1_1.image = [UIImage imageNamed:@"t_1_4.jpg"];
}
解決
あなたは、あなたのUIViewからタッチイベントを処理する必要があります。これを行うには、UIViewののサブクラスを作成し、をtouchesBeganのあなたの実現を追加する必要があります:withEvent:の方法、ここでは最も簡単な例:
// TouchSimpleView.h
@interface TouchSimpleView : UIImageView {
id delegate;
}
@property(retain) id delegate;
@end
@interface NSObject(TouchSimpleView)
-(void)didTouchView:(UIView *)aView;
@end
// TouchSimpleView.m
#import "TouchSimpleView.h"
@implementation TouchSimpleView
@synthesize delegate;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touchesBegan!!! ");
if ( delegate != nil && [delegate respondsToSelector:@selector(didTouchView:)] ) {
[delegate didTouchView:self];
}
[super touchesBegan:touches withEvent:event];
}
@end
あなたがタッチを処理したい場合、あなたは、たとえば、このクラスのビューを使用することができます:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window makeKeyAndVisible];
touchView = [[TouchSimpleView alloc] initWithFrame:CGRectMake(50, 50, 200, 300)];
touchView.delegate = self;
[window addSubview:touchView];
imageView =[[UIImageView alloc] initWithFrame:touchView.frame];
imageView.image = [UIImage imageNamed:@"image1.png"];
[touchView addSubview:imageView];
}
-(void)didTouchView:(UIView *)aView{
NSLog(@"view touched, changing image");
imageView.image = [UIImage imageNamed:@"image2.png"];
}
他のヒント
あなたは簡単にUIButtonの代わりにUIImageを置き、メソッドのsetBackgroundImageを使用して、その背景画像を変更することで行うことができる欲しい:forState:。TouchUpInsideイベントハンドラで
別の解決策ます:
.hファイル内の
場所A IBOutlet UIImagView * IMAGEBUTTON;
と
-(IBAction)doSomething:(id)sender;
.mファイルでの
-(IBAction)dosomething:(id)sender {
// your code
[imageButton setImage:[UIImage imageNamed:@""t_1_4.jpg"} forState:UIControlStateNormal];
}
非常に細かい私のコードで動作します。
これは.hファイルで、サブクラスを作成せずに私と一緒に働くあなたはUIImageViewを追加
#import <UIKit/UIKit.h>
@interface YourClassName : UIViewController{
IBOutlet UIImageView *wallpaper;
}
@property (nonatomic, retain) IBOutlet UIImageView *wallpaper;
@end
、その後の.mにあなたの方法を使用することができます。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[wallpaper setImage:[UIImage imageNamed: @"image.png"]];
}
所属していません StackOverflow