2012-10-23 38 views
1

我試圖讓與的UIScrollView將點擊後切換到不同的一個圖像的列表圖像。這種情況是模擬選擇一個圖像。的Xcode:如何點擊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

解決的辦法是:

- (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

1

確保UIImageView財產userInteractionEnabled設置爲YES
默認爲NO

+0

我已經坐在bankImageView.userInteractionEnabled = YES,並沒有幫助。 –

+0

bankImageView不是一個子類圖像視圖。你只在你的'TouchSimpleView'類中實現了'touchesBegan'。 – Mundi

+0

謝謝@Mundi的回答,但我是iOS新手,我不太明白需要修復的問題。 我知道繼承是什麼,但不知道如何在iOS中實現它。 你能否給我提供一些示例代碼作爲答案? –