为什么这段代码不起作用???如果向右或向左滑动,尝试从UIImageView更改图像

时间:2012-05-06 02:20:06

标签: iphone ios xcode uiimageview

我为什么下面的代码不起作用而疯了......

我有一个简单的UIViewController和UIImageView,如果用户向右或向左滑动,我想尝试更改图像。我是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

3 个答案:

答案 0 :(得分:1)

  1. 我看不出你在哪里UIImageView *imgClothes。你应该写一些像imgClothes = [[UIImageView alloc] init(...)];
  2. 这样的东西
  3. 我没有使用UISwipeGestureRecognizer,但有时您应该在.h文件中写下这样的内容:@interface SummerViewController : UIViewController <UIGestureRecognizerDelegate>
  4. 我更喜欢在initWithNibName中进行初始化,而不是ViewDidLoad。但这不应该是你的问题的原因。

答案 1 :(得分:1)

所有代码都适用于更改UIImageView的图像。根据您的代码片段,我发现了两个场景

1.确保将IBOutlet引用从XIB添加到 imgClothes
2.如果符合“1”点,请尝试检查添加到self.view的 imgClothes 引用。

希望以上两种情况能够解决问题。祝你好运。

答案 2 :(得分:1)

不要忘记一件事

1)swipeRight.delegate = self; //将委托分配给滑动对象。

如果您使用的是sdk 3.2或更高版本,则使用UIGestureRecognizer类可以轻松实现。否则请访问以下参考以检测滑动

https://gist.github.com/791725

希望,这会对你有帮助..