繁体   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