0

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

我有一个带有 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
4

3 回答 3

1
  1. 我看不到你在哪里初始化你的UIImageView *imgClothes. 你应该写类似imgClothes = [[UIImageView alloc] init(...)];
  2. 我没有使用 UISwipeGestureRecognizer,但有时你应该在 .h 文件中这样写:@interface SummerViewController : UIViewController <UIGestureRecognizerDelegate>
  3. 我更喜欢在 中进行初始化initWithNibName,而不是在ViewDidLoad. 但这不应该是您的问题的原因。
于 2012-05-06T02:41:11.603 回答
1

您的所有代码对于更改 UIImageView 的图像都是正确的。根据您的代码片段,我发现了两种情况

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

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

于 2012-05-06T02:44:14.847 回答
1

不要忘记一件事

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

如果您使用的是 sdk 3.2 或更高版本,则使用 UIGestureRecognizer 类非常容易。否则请访问以下参考以检测滑动

https://gist.github.com/791725

希望对你有帮助..

于 2012-05-06T02:46:34.460 回答