简单地说,我已经在UIView中使用Interface Builder放置了一个图像。现在我想在触摸该图像时运行方法/功能,例如当应该加载另一个图像时。
我的代码:
- (void)touchesended:(NSSet*) touches withEvent:(UIEvent *)event
{
// UITouch *touch = [touch anyObject];
bild_1_1.image = [UIImage imageNamed:@"t_1_4.jpg"];
}
答案 0 :(得分:2)
通过使用方法setBackgroundImage:forState:在TouchUpInside事件处理程序中放置UIButton而不是UIImage并更改其背景图像,可以轻松完成所需内容。
答案 1 :(得分:2)
您需要处理来自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"];
}
答案 2 :(得分:1)
另一种解决方案:
<。>文件中的
放置一个 IBOutlet UIImagView * imageButton;
和
-(IBAction)doSomething:(id)sender;
<。>文件中的
-(IBAction)dosomething:(id)sender {
// your code
[imageButton setImage:[UIImage imageNamed:@""t_1_4.jpg"} forState:UIControlStateNormal];
}
我的代码非常好
答案 3 :(得分:0)
它可以在不创建子类的情况下与我合作,在.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"]];
}