簡體   English   中英

為什么此代碼不起作用??? 嘗試從UIImageView更改圖像(如果向右或向左滑動)

[英]Why this code doens't work??? trying to change image from UIImageView if swiped right or left

我很瘋狂,為什么下面的代碼不起作用...

我有一個帶有UIImageView的簡單UIViewController,並且想要嘗試在用戶向右或向左滑動時更改圖像。 我是iPhone開發的新手。

謝謝

#import "SummerViewController.h"


@implementation SummerViewController

//@synthesize scroll;
@synthesize imgClothes, images;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)LeftSwiped
{
    NSLog(@"swiped left");
    imgClothes.image = [UIImage imageNamed:[images objectAtIndex:0]];

}

-(void)RightSwiped
{
    NSLog(@"swiped right");
    imgClothes.image = [UIImage imageNamed:[images objectAtIndex:1]];
}

- (void)viewDidLoad
{

    images = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"1.jpg"],
                       [UIImage imageNamed:@"2.jpg"], nil];

    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(LeftSwiped)];

    swipeLeft.numberOfTouchesRequired = 1;
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeft];

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(RightSwiped)];

    swipeRight.numberOfTouchesRequired = 1;
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeRight];





    [super viewDidLoad];


}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

.h文件:

@interface SummerViewController : UIViewController
{
    //IBOutlet UIScrollView *scroll;
    IBOutlet UIImageView *imgClothes;
    NSArray *images;
}

@property (nonatomic, retain) IBOutlet UIImageView *imgClothes;
@property (nonatomic, retain) IBOutlet NSArray *images;

@end
  1. 我看不到您在哪里初始化UIImageView *imgClothes 您應該編寫類似imgClothes = [[UIImageView alloc] init(...)];
  2. 我沒有使用UISwipeGestureRecognizer,但有時您應該在.h文件中編寫如下內容: @interface SummerViewController : UIViewController <UIGestureRecognizerDelegate>
  3. 我更喜歡在initWithNibName中進行initWithNibName ,而不是在ViewDidLoad初始化。 但這不應該引起您的問題。

您所有的代碼對於更改UIImageView的圖像都是正確的。根據您的代碼片段,我發現了兩種情況

1.確保將IBOutlet參考從XIB添加到imgClothes
2.如果“ 1”點符合,請嘗試檢查是否將您的imgClothes參考添加到self.view

希望以上兩種情況都能解決這個問題。

不要忘記一件事

1) swipeRight.delegate = self; //將委托分配給滑動對象。

如果您使用的是sdk 3.2或更高版本,則使用UIGestureRecognizer類非常容易,否則請訪問以下參考以檢測滑動

https://gist.github.com/791725

希望這個能對您有所幫助..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM