我正在尝试使用单击后切换到不同图像的图像列表来创建UIScrollView。案例是模拟选择图像。
我尝试使用UIButton代替UIImage,切换图片非常容易,但是当我点击按钮时,我无法滚动它们。只有当我点击按钮时才会滚动。
我尝试使用UIImages并且很容易滚动,但点击后我无法切换图像。
我挖了一点,发现了以下帖子:Xcode: How to change Image on Touching at an Image (same Position)?
这似乎是我需要的东西,但我做错了。
我的代码:
//TouchSimpleView.h
#import <UIKit/UIKit.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;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touchesBagan");
if(delegate != nil && [delegate respondsToSelector:@selector(didTouchView:)]) {
[delegate didTouchView:self];
}
[super touchesBegan:touches withEvent:event];
}
@end
我正在使用上面那样:
// ViewController.h
#import <UIKit/UIKit.h>
#import "TouchSimpleView.h"
@interface ViewController : UIViewController {
TouchSimpleView *touchView;
UIImageView *bankImageView;
}
@property (nonatomic, retain) TouchSimpleView *touchView;
@property (nonatomic, retain) UIImageView *bankImageView;
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize touchView;
@synthesize bankImageView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
touchView = [[TouchSimpleView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
touchView.delegate = self;
[self.view addSubview:touchView];
bankImageView = [[UIImageView alloc] initWithFrame:touchView.frame];
bankImageView.image = [UIImage imageNamed:@"1.jpg"];
[touchView addSubview: bankImageView];
}
- (void)didTouchView:(UIView *)aView {
NSLog(@"view touched; changing image");
}
@end
我在开始时没有提到UIScrollView,但我想让这个简单的例子工作,而不是将touchView添加到UIScrollView。
我是iOS编程的初学者。 请指教。
答案 0 :(得分:1)
确保UIImageView
属性userInteractionEnabled
设置为YES
默认值为NO
。
答案 1 :(得分:0)
解决方案是:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
touchView = [[TouchSimpleView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
touchView.delegate = self;
touchView.userInteractionEnabled = YES;
touchView.image = [UIImage imageNamed:@"1.jpg"];
[self.view addSubview:touchView];
}
谢谢@Mundi