How to implement a UIPageControl properly? - ios

I have 3 minor issues related to implementing a UIPageControl. I'm not using a UIPageViewController, so I would not like to use that, if possible.
I have implemented a UIPageControl, where, when a user swipes either left or right on the view, it will move to the next "page" and display a different image.
Here is the following code:
ViewController.h:
#property (nonatomic) NSInteger Count;
#property (strong, nonatomic) IBOutlet UIPageControl *Control;
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UILabel *label;
#property (strong, nonatomic) UISwipeGestureRecognizer *swipeRight, *swipeLeft;
#property (strong, nonatomic) NSArray *array;
ViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.array = #[#"page1", #"page2", #"page3", #"page4"];
self.swipeRight = [ [UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(Right:)];
self.swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:self.swipeRight];
self.swipeLeft = [ [UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(Left:)];
self.swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:self.swipeLeft];
self.Control.numberOfPages = 3;
self.Control.currentPage = 0;
}
-(void)Right: (UITapGestureRecognizer *)sender
{
self.Count = self.Count - 1;
if (self.Count > 3)
{
self.Count = 1;
}
else if (self.Count < 1)
{
self.Count = 3;
}
if (self.Count == 1)
{
self.Control.currentPage = 0;
self.imageView.image = [UIImage imageNamed:[self.array objectAtIndex:self.Control.currentPage]];
// self.label.text = #"this is page 1";
}
else if (self.Count == 2)
{
self.Control.currentPage = 1;
self.imageView.image = [UIImage imageNamed:[self.array objectAtIndex:self.Control.currentPage]];
// self.label.text = #"this is page 2";
}
else if (self.Count == 3)
{
self.Control.currentPage = 2;
self.imageView.image = [UIImage imageNamed:[self.array objectAtIndex:self.Control.currentPage]];
// self.label.text = #"this is page 3";
}
}
-(void)Left: (UITapGestureRecognizer *)sender
{
self.Count = self.Count + 1;
if (self.Count > 3)
{
self.Count = 1;
}
else if (self.Count < 1)
{
self.Count = 3;
}
if (self.Count == 1)
{
self.Control.currentPage = 0;
self.imageView.image = [UIImage imageNamed:[self.array objectAtIndex:self.Control.currentPage]];
//self.label.text = #"this is page 1";
}
else if (self.Count == 2)
{
self.Control.currentPage = 1;
self.imageView.image = [UIImage imageNamed:[self.array objectAtIndex:self.Control.currentPage]];
//self.label.text = #"this is page 2";
}
else if (self.Count == 3)
{
self.Control.currentPage = 2;
self.imageView.image = [UIImage imageNamed:[self.array objectAtIndex:self.Control.currentPage]];
// self.label.text = #"this is page 3";
}
}
The first issue: how do I make the view display the first image at index 0 on launch?
Right now, if you start the app initially, the image is blank on screen even though the page control shows the current view as being highlighted with the little dot. You have to swipe left to get the first image in index 0 to display.
The second issue: how do I add a scroll transition style animation when swiped left or right?
Right now, if you swipe either left or right, the image transition is instant, and you don't see that swiping animation where one image pushes the other image out of the view.
The third issue: how do I make the swipe gesture recognition not be the whole view area, but only be swipeable if you swipe on the upper portion of the view?
Feel free to download the project code as it's just a template that I'm using:
project code
Thanks

Related

Xcode - IB elements not shown in my view at runtime

I've got a very weird problem with my iOS project.
I have a UIViewController with some labels and buttons and when user enters this view I programmatically build a gameboard (it's the minesweeper game).
What I wanted to do now is add a simple element (in my case a segmented control but i tried also with a button and doesn't work) at the bottom or at the beginning of the board.
When I add something from the Interface Builder I can see that in the storyboard but when I run the app puff, it's disappeared!
View contains only the "old" elements and the new one is not shown.
Yes I made a IBOutlet:
#property (weak, nonatomic) IBOutlet UISegmentedControl *clickTypeSegmentedControl;
And yes I checked if references of segemented control are ok.
I can't really understand what is wrong, if someone can help I'll be very grateful.
** EDIT: I added code of the ViewController, there are some other methods I left out because they only handle the game. I repeat: even if I add a simple button with no actions, it will not be shown.
#import "GameViewController.h"
#import "GameBoardModel.h"
#import "ScoreViewController.h"
#import <AVFoundation/AVFoundation.h>
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#interface GameViewController ()
#property (weak, nonatomic) IBOutlet UILabel *timerLabel;
#property (weak, nonatomic) IBOutlet UILabel *bombsLabel;
#property (weak, nonatomic) IBOutlet UIButton *restartButton;
#property(nonatomic, strong) AVAudioPlayer *soundEffects;
#property (weak, nonatomic) IBOutlet UISegmentedControl *clickTypeSegmentedControl;
#end
#implementation GameViewController
#synthesize difficulty, timer, playerName, scoreToAdd, clickTypeSegmentedControl;
double secondsPassed=-1.0f;
int seconds=0;
int totalRowsCols=0, totalMines=0, heightWidth=0, clicKNumber=0;
static NSString * const IMAGE_NAME_FLAG = #"flag.png";
static NSString * const IMAGE_NAME_BOMB_X = #"bomb.png";
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.hidesBackButton = YES;
UIBarButtonItem *backButton =[[UIBarButtonItem alloc]initWithTitle:#"MenĂ¹" style:UIBarButtonItemStyleBordered target:self action:#selector(popAlertAction:)];
self.navigationItem.leftBarButtonItem=backButton;
clickTypeSegmentedControl.selectedSegmentIndex = 0;
rootController = (BombsSeekerViewController *)[self.navigationController.viewControllers objectAtIndex:0];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
playerName = [defaults objectForKey:#"NomeGiocatore"];
scoreToAdd = [[NSMutableDictionary alloc]init];
[self createGameBoard:difficulty];
[self newGame:nil];
}
-(void) newGame:(UIButton *)sender {
[self.view.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
clicKNumber=0;
secondsPassed=0;
self.timerLabel.text = [self labelString:secondsPassed];
self.game = [[Game alloc] initWithWidth:totalRowsCols AndHeight:totalRowsCols AndMineCount:totalMines];
self.buttonArray = [[NSMutableArray alloc] init];
[self.restartButton addTarget:self action:#selector(newGame:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.restartButton];
[self.view addSubview:self.timerLabel];
[self.view addSubview:self.bombsLabel];
for(int i = 0; i < totalRowsCols; i++) {
for (int j = 0; j < totalRowsCols; j++) {
self.button = [[Tile alloc] initWithLocation: CGPointMake(j,i) andHW:heightWidth andBlock:self.game.board[j][i] andTag:(i*totalRowsCols+j)];
[self.buttonArray addObject:self.button];
[self.view addSubview:self.button];
[self.button addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
}
[self.timer invalidate];
}
- (void) createGameBoard:(int)diff{
switch (diff) {
case 1:
totalRowsCols = 6;
totalMines = 2;
heightWidth = 44;
break;
case 2:
totalRowsCols = 8;
totalMines = 16;
heightWidth = 35;
break;
case 3:
totalRowsCols = 10;
totalMines = 25;
heightWidth = 29;
break;
}
self.flagCount = totalMines;
_bombsLabel.text = [NSString stringWithFormat:#"%d",self.flagCount];
}
-(NSString *) labelString: (int) num {
if(num < 10) {
return [NSString stringWithFormat:#"00%i",num];
}
else if(self.timeCount.intValue < 100) {
return [NSString stringWithFormat:#"0%i",num];
}
else if(self.timeCount.intValue < 1000) {
return [NSString stringWithFormat:#"%i",num];
}
else
return #"---";
}
-(void) click:(Tile *)sender {
if(clicKNumber <1){
[self refreshLabel:self.timer];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(refreshLabel:)
userInfo:nil
repeats:YES];
clicKNumber++;
}
if(self.game.gameStatus == STATUS_LOST || self.game.gameStatus == STATUS_WON) return;
if (self.clickTypeSegmentedControl.selectedSegmentIndex == 0 && sender.block.marking == MARKING_BLANK) {
[self.game clickedAtColumn: sender.point.x AndRow: sender.point.y];
for(Tile *b in self.buttonArray) {
if(b.block.marking == MARKING_CLICKED) {
b.enabled = NO;
}
else if(b.block.marking == MARKING_BLANK) {
[b setTitle:#"" forState:UIControlStateNormal];
[b setImage:nil forState:UIControlStateNormal];
}
}
}
else if (self.clickTypeSegmentedControl.selectedSegmentIndex == 1){
if(sender.block.marking == MARKING_BLANK && self.flagCount > 0) {
sender.block.marking = MARKING_FLAGGED;
self.flagCount--;
_bombsLabel.text = [NSString stringWithFormat:#"%d",self.flagCount];
[sender setImage:[UIImage imageNamed:IMAGE_NAME_FLAG] forState:UIControlStateNormal];
}
else if(sender.block.marking == MARKING_FLAGGED) {
sender.block.marking = MARKING_BLANK;
self.flagCount++;
_bombsLabel.text = [NSString stringWithFormat:#"%d",self.flagCount];
[sender setImage:[UIImage imageNamed:#"tile.png"] forState:UIControlStateNormal];
}
}
if(self.game.gameStatus == STATUS_LOST) [self gameLost:sender];
else if(self.game.gameStatus == STATUS_WON) [self gameWon];
}
If this is what I think it is, you should not be doing this:
[self.view.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
When the viewDidLoad is called, the newGame method is called, which removes al subviews from Superview. Including the ones added in Storyboard.
Make sure controller in storyboard is linked with the right controller class.
You call this method during -viewDidLoad:
-(void) newGame:(UIButton *)sender {
[self.view.subviews makeObjectsPerformSelector: #selector(removeFromSuperview)];
//...
}
Thus, anything you put in your nib is getting removed after it loads.

How to display images on button action

I have 10 UIImages. When I click the UIButton it displaying under UIScrollView. But I need to implement theUIButtonlike **Next**, ifUIButtonis clicked first time, it displays the firstUIImage`, then after that, on click it displays next image. If I click the back button, the previous image should be displayed.
int currentIndex = 0;
int MAX_COUNT;
NSMutableArray *imageName = [[NSMutableArray alloc] initWithObjects:
#"spices.jpg",
#"spice_powder.jpg",
#"turmeric.jpg",
#"whynani_img3.jpg",
#"spice_blends.jpg",
#"products1.png", nil];
currentIndex = currentIndex + 1;
if(currentIndex > MAX_COUNT) {
currentIndex = MAX_COUNT;
}
for (int i = 0; i<[imageName count]; i++ ) {
UIImageView *mmageView =
[[UIImageView alloc] initWithFrame:CGRectMake(200,200,350,350)];
[mmageView setImage:[UIImage imageNamed:[imageName objectAtIndex:i]]];
[self.view addSubview:mmageView];
}
Declare a global imageView and an int in interface file
UIImageView *imgView;
int index;
In viewDidLoad:
index = 0;
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(200,200,350,350)];
[imgView setImage:[UIImage imageNamed:[imageName objectAtIndex:index]]];
[self.view addSubView:imgView];
In Next Button Action
-(void)nextButtonAction
{
++index;
[previousBtn setEnabled:YES];
if (index > [imageName count])
{
index = [imageName count] - 1;
[nextBtn setEnabled:NO];
}
[imgView setImage:[UIImage imageNamed:[imageName objectAtIndex:index]]];
}
In Previous Button Action
-(void)previousButtonAction
{
--index;
[nextBtn setEnabled:YES];
if (index < 0)
{
index = 0;
[previousBtn setEnabled:NO];
}
[imgView setImage:[UIImage imageNamed:[imageName objectAtIndex:index]]];
}
You can do the same using a UIViewController having 2 UIButtons with custom images depicting forward and back along with UIImageView. On selecting the next / back button load the appropriate image. The image name has to be stored in an NSArray.
Hope this helps.
Edit: sample code as given below,
In .h file
#property(nonatomic, weak) UIImageView *imageView;
#property(nonatomic, weak) UIButton *nextButton;
#property(nonatomic, weak) UIButton *backButton;
(IBAction)btnNextBtn:(id)sender;
(IBAction)btnBackBtn:(id)sender;
In .m file
(void)viewDidLoad {
currentIndex = 0;
NSMutableArray *imageName = [[NSMutableArray alloc] initWithObjects:#"Myprofile.png",
#"great_ideas_wordle2.png", #"Review.png",
#"collaborate.png", nil];
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(200,200,350,350)];
[imageView setImage:[UIImage imageNamed:[imageName objectAtIndex:currentIndex]]];
[self.view addSubView:imageView];
}
(IBAction)btnNextBtn:(id)sender {
currentIndex = currentIndex + 1;
if(currentIndex > MAX_COUNT) {
currentIndex = MAX_COUNT;
}
// load the image view with the currentIndex from the array.
[imageView setImage:[UIImage imageNamed:[imageName objectAtIndex:currentIndex]]];
}
(IBAction)btnBackBtn:(id)sender {
currentIndex = currentIndex - 1;
if (currentIndex < 0) {
currentIndex = 0;
}
// load the image view with the currentIndex from the array.
[imageView setImage:[UIImage imageNamed:[imageName objectAtIndex:currentIndex]]];
}
write this in .h file
#property (nonatomic,retain)IBOutlet UIImageView *imageview1;
#property (nonatomic,retain)IBOutlet UIButton *pre,*next;
#property (nonatomic,retain) NSArray *images;
#property (nonatomic) int currentindex;
-(IBAction)prebtn:(id)sender;
-(IBAction)nextbtn:(id)sender;
write this code in .m file
#implementation ViewController
#synthesize images;
#synthesize currentindex;
#synthesize pre,next;
#synthesize imageview1;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.currentindex = 0;
self.images = [[NSArray alloc] initWithObjects:#"images-2.jpeg",#"images- 3.jpeg",#"images.jpeg", nil];
imageview1.image = [UIImage imageNamed:#"images-2.jpeg"];
[pre setEnabled:NO];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)nextbtn:(id)sender{
currentindex = currentindex + 1;
[pre setEnabled:YES];
if (currentindex >= [images count])
{
currentindex = currentindex - 1;
[next setEnabled:NO];
}
imageview1.image = [UIImage imageNamed:[images objectAtIndex:currentindex]];
}
-(IBAction)prebtn:(id)sender{
currentindex = currentindex - 1;
[next setEnabled:YES];
if(currentindex < 0)
{
currentindex = 0;
[pre setEnabled:NO];
}
imageview1.image = [UIImage imageNamed:[images objectAtIndex:currentindex]];
}
#end
Try with this code
.h file
#property(nonatomic, strong) UIImageView *imageView;
#property(nonatomic, strong) UIButton *nextButton;
#property(nonatomic, strong) UIButton *previousButton;
#property(nonatomic, strong) NSMutableArray *imagesArrayName;
#property(nonatomic) int currentIndex;
-(IBAction)btnNextImage:(id)sender;
-(IBAction)btnPreviousImage:(id)sender;
.m file
- (void)viewDidLoad {
[super viewDidLoad];
self.currentIndex = 0;
NSMutableArray *imagesArrayName = [[NSMutableArray alloc] initWithObjects:
#"spices.jpg",
#"spice_powder.jpg",
#"turmeric.jpg",
#"whynani_img3.jpg",
#"spice_blends.jpg",
#"products1.png", nil];
[self.nextButton addTarget:self action:#selector(btnNextImage:) forControlEvents:UIControlEventTouchUpInside];
[self.previousButton addTarget:self action:#selector(btnPreviousImage:) forControlEvents:UIControlEventTouchUpInside];
[self.imageView setImage[UIImage imageNamed:(NSString*)[imagesArrayName objectAtIndex:currenIndex]]];
[self.previousButton setEnabled:FALSE];
}
-(IBAction)btnNextImage:(id)sender {
self.currentIndex = self.currentIndex + 1;
[self.imageView setImage[UIImage imageNamed:(NSString*)[imagesArrayName objectAtIndex:currenIndex]]];
if (self.currentIndex == [self.imagesArrayName count] - 1) {
[self.nextButton setEnabled:FALSE];
}
[self.previousButton setEnabled:TRUE];
}
-(IBAction)btnPreviousImage:(id)sender{
self.currentIndex = self.currentIndex - 1;
[self.imageView setImage[UIImage imageNamed:(NSString*)[imagesArrayName objectAtIndex:currenIndex]]];
if (self.currentIndex == 0) {
[self.previousButton setEnabled:FALSE];
}
[self.nextButton setEnabled:TRUE];
}

NSArray index beyond bounds error

I have created a simple image browser with two buttons to view the next and the previous images.
Here's the code.
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) NSArray *images;
#property (assign, nonatomic) NSInteger imageIndex;
#property (strong, nonatomic) UIBarButtonItem *nextButton;
#property (strong, nonatomic) UIBarButtonItem *prevButon;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Adding Next and Previous buttons
self.nextButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"next"] style:UIBarButtonItemStylePlain target:self action:#selector(nextButtonPressed)];
self.prevButon = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"previous"] style:UIBarButtonItemStylePlain target:self action:#selector(previousButtonPressed)];
self.navigationItem.rightBarButtonItems = #[self.nextButton, self.prevButon];
// Loading images
self.images = #[
[UIImage imageNamed:#"1"],
[UIImage imageNamed:#"2"],
[UIImage imageNamed:#"3"],
[UIImage imageNamed:#"4"],
[UIImage imageNamed:#"5"],
[UIImage imageNamed:#"6"],
[UIImage imageNamed:#"7"],
[UIImage imageNamed:#"8"],
[UIImage imageNamed:#"9"]
];
self.imageIndex = 0;
self.imageView.image = self.images[self.imageIndex];
}
- (void)nextButtonPressed
{
self.imageIndex++;
self.imageView.image = self.images[self.imageIndex];
}
- (void)previousButtonPressed
{
self.imageIndex--;
self.imageView.image = self.images[self.imageIndex];
}
#end
My problem is say if I tap next button after the last image or previous button when the first image, it'll throw a index beyond bounds error.
How can I stop this from happening?
Thank you.
You have to check whether the index is present in your index.
You can make the verification in your nextButtonPressed and previousButtonPressed methods:
- (void)nextButtonPressed
{
if (imageIndex < ([self.images count] - 1))
{
self.imageIndex++;
self.imageView.image = self.images[self.imageIndex];
}
}
- (void)previousButtonPressed
{
if (imageIndex >= 1)
{
self.imageIndex--;
self.imageView.image = self.images[self.imageIndex];
}
}
For information the NSArray raises an NSRangeException if the index is beyond the end of the array (see the documentation).
You are keeping track of the current image index, which is good, because you can use that to check if there is a next image or a previous by using the image arrays count property.
- (void)nextButtonPressed
{
if ( self.imageIndex < self.images.count - 1) {
self.imageIndex++;
self.imageView.image = self.images[self.imageIndex];
}
}
- (void)previousButtonPressed
{
if ( self.imageIndex > 0 ) {
self.imageIndex--;
self.imageView.image = self.images[self.imageIndex];
}
}
Another alternative is starting over when you reach the last image.
- (void)nextButtonPressed
{
if ( self.imageIndex < self.images.count - 1) {
self.imageIndex++;
} else {
self.imageIndex = 0
}
self.imageView.image = self.images[self.imageIndex];
}
- (void)previousButtonPressed
{
if ( self.imageIndex > 0 ) {
self.imageIndex--;
} else {
self.imageIndex = self.images.count - 1;
}
self.imageView.image = self.images[self.imageIndex];
}
You can use modulus like this - so it wraps around on itself.
This way you never need to disable buttons and it also makes it easier for the user to get from one end of the list to the other more efficiently.
replace the following line
self.imageIndex++;
with
self.imageIndex = (self.imageIndex + 1) % [self.images count];
and where you have the following line
self.imageIndex--;
replace with
self.imageIndex = (self.imageIndex + [self.images count] - 1) % [self.images count];
A good UI habit will be to disable the next (or previous) button once you reach the last image (and of course prevent the overflow in the array):
- (void)nextButtonPressed
{
self.imageIndex++;
self.imageView.image = self.images[self.imageIndex];
[self.previousButton setEnabled:YES];
if (self.imageIndex == [self.images count] - 1) {
[self.nextButton setEnabled:NO];
return ;
}
}
- (void)previousButtonPressed
{
self.imageIndex--;
self.imageView.image = self.images[self.imageIndex];
[self.nextButton setEnabled:YES];
if (self.imageIndex == 0) {
[self.previousButton setEnabled:NO];
return ;
}
}
Since you start with index = 0 you should disable the previous button in viewDidLoad method (as you do not have more previous images until you press next) or do it directly in IB if possible

Next button image array xcode

I'm trying to code an app in Xcode 4, with storyboarding.
My project is something like this:
1 table view controller
1 detail view controller with 4 buttons,
and say 6 images( 1-1.jpg/1-2.jpg/1-3.jpg, and 2-1.jpg/2-2.jpg/2-3.jpg.
I have got my app to show the images(1-1.jpg and 2-1.jpg) in the array when clicking the cells.
And this is my code:
// TableViewController.m:
#synthesize myTitle = _myTitle;
#synthesize myScene = _myScene;
#synthesize myImages = _myImages;
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTitle = [[NSArray alloc] initWithObjects:#"Chicken", #"Flower", nil];
self.myScene = [[NSArray alloc] initWithObjects:#"1", #"2", nil];
self.myImages = [[NSArray alloc] initWithObjects:#"1-1.jpg", #"2-1.jpg", nil];
}
// DetailViewController.m
#synthesize titleLabel = _titleLabel;
#synthesize sceneLabel = _sceneLabel;
#synthesize imageView = _imageView;
#synthesize myDetailModel = _myDetailModel;
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = self.titleLabel.text = [self.myDetailModel objectAtIndex:0];
self.sceneLabel.text = [self.myDetailModel objectAtIndex:1];
self.imageView.image = [UIImage imageNamed:
[self.myDetailModel objectAtIndex:2]];
I want my DetailView page to show the next or previous image(1-2.jpg/1-3.jpg... / 2-2.jpg, 2-3.jpg...) each time I press next or previous (black)button,
and to show next or previous scene(chicken scene and flower scene) when I press another (green)buttons,
like https://dl.dropboxusercontent.com/u/7493131/q3.jpg
I don't know how to array 1-2.jpg, 1-3.jpg, 2-2.jpg and 2-3.jpg and what to do with them.
I am so new that I would like some example code to help please to study how it works,
and how I can implement similar within my app. Thank you.
-(IBAction)rightClick{
if (imageArrayObj.count > 0) {
currentIndex++;
if (currentIndex > imageArrayObj.count - 1) {
currentIndex = 0;
}
imageViewObj.image = [imageArrayObj objectAtIndex:currentIndex];
}
}
It's working properly ..... Use this and currentIndex is integer declare " int currentIndex;" and assign value in view did load "currentIndex = 0;"
You need to create an instance int variable idx to keep track of which image you are handling and assign two IBActions to those buttons :
// This is for your fighter case
- (IBAction)presentPreviousImage:(id)sender {
idx --;
if (idx == 2) {
self.imageView.image = [UIImage imageNamed:#"1-3.jpg"];
} else if (idx == 1) {
self.imageView.image = [UIImage imageNamed:#"1-2.jpg"];
} else if (idx == 0) {
self.imageView.image = [UIImage imageNamed:#"1-1.jpg"];
idx = 2;
}
}
- (IBAction)presentNextImage:(id)sender {
idx ++;
if (idx == 0) {
self.imageView.image = [UIImage imageNamed:#"1-2.jpg"];
} else if (idx == 1) {
self.imageView.image = [UIImage imageNamed:#"1-3.jpg"];
} else if (idx == 2) {
self.imageView.image = [UIImage imageNamed:#"1-1.jpg"];
idx = 0;
}
}

SDWebimage scrolling

I use SDWebimage to load and cache pictures, and now I am looking for a way to swipe/scroll through the images. I've tried different approaches but I can't seem to get it working, can someone help me with this?
You just do your scrolling image browser as you otherwise would, but instead of setting the image property synchronously, you just call the SDWebImage method setImageWithURL (from its UIImageView category).
To show you a quick and dirty implementation, create a UIScrollView, turn on paging, and in viewDidLoad you can set the content size and load the first image, like so:
[self.scrollView setContentSize:CGSizeMake(self.view.bounds.size.width * [self.objects count],
self.view.bounds.size.height)];
dispatch_async(dispatch_get_main_queue(), ^{
ImageBrowserObject *object = self.objects[0];
[object scrollView:self.scrollView addImageViewIfNeededForIndex:0];
});
You also want to set up your controller as a delegate for that scroll view and then handle the scrollViewDidScroll event:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
static NSInteger lastKnownIndex = -1;
NSInteger currentIndex = scrollView.contentOffset.x / scrollView.frame.size.width + 0.5f;
NSInteger nextIndex = currentIndex + 1;
NSInteger prevIndex = currentIndex - 1;
if (prevIndex < 0) prevIndex = 0;
if (currentIndex == lastKnownIndex)
return;
// add the imageviews we need, remove the ones we don't
[self.objects enumerateObjectsUsingBlock:^(ImageBrowserObject *object, NSUInteger idx, BOOL *stop) {
if (idx >= prevIndex && idx <= nextIndex)
[object scrollView:scrollView addImageViewIfNeededForIndex:idx];
else
[object scrollView:scrollView removeImageViewIfNeededForIndex:idx];
}];
lastKnownIndex = currentIndex;
}
And my ImageBrowserObject is defined as follows:
#interface ImageBrowserObject : NSObject
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSURL *url;
#property (nonatomic, weak) UIImageView *imageView;
#end
#implementation ImageBrowserObject
- (id)initWithTitle:(NSString *)title URL:(NSURL *)url
{
self = [super init];
if (self) {
_title = title;
_url = url;
}
return self;
}
- (void)scrollView:(UIScrollView *)scrollView addImageViewIfNeededForIndex:(NSInteger)index
{
if (self.imageView)
return;
CGRect frame = CGRectMake(index * scrollView.frame.size.width,
0.0,
scrollView.frame.size.width,
scrollView.frame.size.height);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
[scrollView addSubview:imageView];
[imageView setImageWithURL:self.url placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
self.imageView = imageView;
}
- (void)scrollView:(UIScrollView *)scrollView removeImageViewIfNeededForIndex:(NSInteger)index
{
if (!self.imageView)
return;
[self.imageView removeFromSuperview];
self.imageView = nil;
}
#end
This is a pretty simplistic implementation, but I suspect you get the idea.

Resources