2013-12-07 29 views
0

我試圖在2張圖像之間滑動。手勢被識別,但不顯示圖像。檢測到滑動手勢,但不顯示圖像(UISwipeGestureRecognizer,UIImageView和NSArray)

我正在嘗試以編程方式執行此操作。起初,我正在創建一個UIImageView,我已經在.h文件中聲明。該圖像視圖稱爲imageView。

在.m文件中,我正在實現該視圖。我還添加了滑動左右手勢識別器。滑動觸發一個名爲handleSwipe的動作。我知道滑動被識別是因爲在發生滑動時在輸出日誌中顯示的NSLog語句。

handleSwipe操作從NSArray獲取圖像,並根據我們是向左還是向右滑動來顯示它。該方法將圖像放在imageView中。

我有的問題是,我的是handleSwipe不顯示任何圖像。

我的代碼如下:

@implementation firstStartViewController 
@synthesize imageView; 
int imageIndex = 1; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
if (self) { 
    // Custom initialization 
} 
return self; 
} 
- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
// Do any additional setup after loading the view. 
self.view.backgroundColor = [UIColor whiteColor]; 


imageView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)); 

imageView.center = CGPointMake(CGRectGetWidth(self.view.bounds)/2.0f, CGRectGetHeight(self.view.bounds)/2.0f + 75); 

imageView.userInteractionEnabled = YES; 

[self.view addSubview:imageView]; 



UISwipeGestureRecognizer *swipeleft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; 
swipeleft.direction = UISwipeGestureRecognizerDirectionLeft; 
[self.view addGestureRecognizer:swipeleft]; 



UISwipeGestureRecognizer *swiperight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; 
swiperight.direction = UISwipeGestureRecognizerDirectionRight; 
[self.view addGestureRecognizer:swiperight]; 


UIBarButtonItem *dismiss_btn = [[UIBarButtonItem alloc] initWithTitle:@"Start App" style:UIBarButtonItemStylePlain target:self action:@selector(dismissModal:)]; 

self.navigationItem.rightBarButtonItems = [NSMutableArray arrayWithObjects:dismiss_btn, nil]; 
} 


- (IBAction)handleSwipe:(UIGestureRecognizer *)sender { 

NSLog(@"Swiped"); 


NSArray *images=[[NSArray alloc] initWithObjects: 
       @"image1.png", 
       @"image2.png", nil]; 

UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction]; 

switch (direction) { 
    case UISwipeGestureRecognizerDirectionLeft: 
     imageIndex++; 
     break; 
    case UISwipeGestureRecognizerDirectionRight: 
     imageIndex--; 
     break; 
    default: 
     break; 
} 
imageIndex = (imageIndex < 0) ? ([images count] -1): imageIndex % [images count]; 
imageView.image = [UIImage imageNamed:[images objectAtIndex:imageIndex]]; 
} 

回答

0

你應該在你viewDidLoad方法設置你的imageIndex指定的爲默認值(也許爲0)。

只需在viewDidLoad中添加此行即可。

imageIndex = 0; 
+0

@Shiri:我編輯了我的代碼,向您展示了我初始化imageIndex的位置。它位於執行部分的下方,而不是viewDidLoad。讓我試試你的建議。 – Armand

+0

@Shiri:我發現了這個問題。這是因爲NSArray正在返回(空)值。現在我需要找出如何解決它。 – Armand

+0

我已經在這裏打開一個新的話題http://stackoverflow.com/questions/20458808/nsarray-returning-null-value-even-though-right-number-of-objects-is-counted-and – Armand