簡單作法:
直接用imageview給他個animation,
banerArray = [NSArray arrayWithObjects:
[UIImage imageNamed:@"320_70b01.png"],
[UIImage imageNamed:@"320_70b02.png"],
[UIImage imageNamed:@"320_70b03.png"],
[UIImage imageNamed:@"320_70b04.png"],
nil];
這邊傳近來的array就是把uiimage包成array:之後下面就可以讓他開始動畫了,
-(void)startADBanerWithArray:(NSArray *)array
{
self.myImageView.animationImages = array ;
self.myImageView.animationRepeatCount = 0;
self.myImageView.animationDuration= 8.0;
[self.myImageView startAnimating];
}
不過這邊有個小小遺憾,如果我想讓user可以按下去呢?
加入手勢:
UITapGestureRecognizer *tapGestureRecognizer;
tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
tapGestureRecognizer.numberOfTapsRequired = 1;
self.myImageView.userInteractionEnabled = YES;//最重要,一定要加
[self.myImageView addGestureRecognizer:tapGestureRecognizer];
不過,這邊用的方法,如果圖片一多,容易crash,
下面我用timer來處理,而且手勢讓user點下去後,我可以知道確切user點了哪一個圖片,
更smart了
@property (nonatomic, strong) NSArray *bannerImagesArray;
@property (nonatomic ,strong) NSTimer *timer;
@property NSUInteger currentImageIndex;
@property (weak, nonatomic) IBOutlet UIImageView *image;
一樣,把uiimage包成array,丟進來的個方法中:
之後利用timer去換圖片
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setup];
self.bannerImagesArray = [NSArray arrayWithObjects:
[UIImage imageNamed:@"320_70b01.png"],
[UIImage imageNamed:@"320_70b02.png"],
[UIImage imageNamed:@"320_70b03.png"],
[UIImage imageNamed:@"320_70b04.png"],
nil];
[self setBannerImagesArray:self.bannerImagesArray];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
用timer上圖片,先把第一張給他
- (void)setBannerImagesArray:(NSArray *)bannerImagesArray
{
_bannerImagesArray = bannerImagesArray;
[self.timer invalidate];
self.currentImageIndex = 0;
self.image.image = [self.bannerImagesArray objectAtIndex:self.currentImageIndex];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(displayNextImage)
userInfo:nil
repeats:YES];
}
先把手勢加入
- (void)setup
{
self.image.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClicked)];
[self.image addGestureRecognizer:tapGesture];
self.bannerImagesArray = nil;
}
這樣就可以知道手勢是點到哪一個圖片了
- (void)imageClicked
{
NSLog(@"Image clicked index: %lu", (unsigned long)self.currentImageIndex);
}
繼續用timer上圖片給他
- (void)displayNextImage
{
self.currentImageIndex = (self.currentImageIndex + 1) % self.bannerImagesArray.count;
NSLog(@"Current Image Index %lu", (unsigned long)self.currentImageIndex);
self.image.image = [self.bannerImagesArray objectAtIndex:self.currentImageIndex];
}
沒有留言:
張貼留言