Change image in UIImageView when UIButton is pressed programmatically - ios

I am trying to change the image inside an imageview when a UIButton is pressed. I need at least three or 4 clicks before the image is changed. What is wrong ?
Here is the code I am using
#interface ARViewController ()
#property (nonatomic, strong) NSMutableArray *pepsiPhotos;
#property (nonatomic, strong) UIImageView *imageView;
#end
#implementation ARViewController
{
IBOutlet UIView *overlayView;
int currentImageIndex;
}
#synthesize imageView;
- (void)viewDidLoad
{
[super viewDidLoad];
_pepsiPhotos = [NSMutableArray arrayWithObjects:#"pepsican.jpeg",
#"pepsilight.jpeg", #"7up.jpeg", #"mirinda.jpeg", nil];
overlayView = [[UIView alloc] initWithFrame:CGRectMake(50.f, 80.f, 240.f, 275.f)];
[overlayView setHidden:YES];
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.f, 20.f, 200.f, 150.f)];
[overlayView addSubview:imageView];
[self.view addSubview:overlayView];
currentImageIndex = 0;
[self showImages];
}
-(void) showImages
{
//
[overlayView setHidden:NO];
[overlayView setBackgroundColor:[UIColor clearColor]];
[overlayView setUserInteractionEnabled:YES];
UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
nextButton.frame = CGRectMake(165.f, 260.f, 40.f, 40.f);
[nextButton setTitle:#"Next" forState:UIControlStateNormal];
[nextButton addTarget:self action:#selector(nextButtonPressed:) forControlEvents:UIControlEventTouchDown];
[nextButton setUserInteractionEnabled:YES];
[overlayView addSubview:nextButton];
[overlayView bringSubviewToFront:nextButton];
UIButton *previousButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
previousButton.frame = CGRectMake(0, 260.f, 40.f, 40.f);
[previousButton setTitle:#"Last" forState:UIControlStateNormal];
[previousButton addTarget:self action:#selector(previousButtonPressed:) forControlEvents:UIControlEventTouchDown];
[previousButton setUserInteractionEnabled:YES];
[overlayView addSubview:previousButton];
[imageView setImage:[UIImage imageNamed:[_pepsiPhotos objectAtIndex:currentImageIndex]]];
[overlayView addSubview:imageView];
[self.view addSubview:overlayView];
}
-(IBAction)nextButtonPressed:(id)sender
{
if (currentImageIndex < [_pepsiPhotos count] -1)
{
currentImageIndex++;
[self performSelectorOnMainThread:#selector(showNextImage) withObject:nil waitUntilDone:NO];
}
}
-(IBAction)previousButtonPressed:(id)sender
{
if (currentImageIndex > 0)
{
currentImageIndex--;
[self performSelectorOnMainThread:#selector(showNextImage) withObject:nil waitUntilDone:NO];
}
}
-(void)showNextImage
{
[imageView setImage:[UIImage imageNamed:[_pepsiPhotos objectAtIndex:currentImageIndex]]];
[overlayView addSubview:imageView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

One problem is that you are saying performSelectorOnMainThread:. If this is an action method from your button, you are on the main thread. Just respond however you want to respond.
Saying performSelectorOnMainThread: when you are already on the main thread can actually cause a delay, because now we have to wait for the main thread to become free before we can run the code.

Related

IOS/Objective-C: Animate Image Change in UIBarButtonItem

I am trying to create an effect where a custom image in a UIBarButtonItem changes to another image. So far, I have been able to get the first image to dissolve with the following code. Can anyone suggest how I could get the second image to fade in at the same time?
//Create barbuttonitem in viewwillappear
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setFrame:CGRectMake(12, 0, 22, 22)];
[b addTarget:self action:#selector(menuButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[b setImage:[UIImage imageNamed:#"firstimage.png"] forState:UIControlStateNormal];
UIBarButtonItem * myBarButton = [[UIBarButtonItem alloc] initWithCustomView:b];
//Animate in viewDidAppaer
[UIView animateWithDuration:1.0
delay:1.0
options:UIViewAnimationOptionCurveEaseIn
animations:^{
self.myBarButton.customView.alpha = 0;
}
completion:^(BOOL finished) {
UIImage *secondImage = [UIImage imageNamed:#"menu2.png"];
[self.myBarButton setImage:secondImage];//THis does not change image
self.myBarButton.customView.alpha = 1;//no animation
}];
You can use something like this
[UIView transitionWithView:self.myBarButton
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ [self.myBarButton setImage:secondImage];}
completion:nil];
Try this code
#interface ViewController ()
{
UIBarButtonItem * myBarButton;
NSTimer *time;
UIButton *b;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setFrame:CGRectMake(12, 0, 22, 22)];
[b addTarget:self action:#selector(menuButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[b setImage:[UIImage imageNamed:#"AddPlus_Yellow.png"] forState:UIControlStateNormal];
myBarButton = [[UIBarButtonItem alloc] initWithCustomView:b];
self.navigationItem.rightBarButtonItem=myBarButton;
time = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector:#selector(onTick:) userInfo: nil repeats:NO];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)onTick:(NSTimer *)timer {
[b setImage:[UIImage imageNamed:#"filter.png"] forState:UIControlStateNormal];
[time invalidate];
}

Segment control background color not getting changed

I am working on a project where I am using custom buttons for login and signup.
All I want is when I click on login, the color of signup button changes and when I click on signup button again the color of login button changs back.
I tried the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
// [self.view setNuiClass:#"ViewInit"];
// Do any additional setup after loading the view from its nib.
UIImageView *img = [[UIImageView alloc ] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
img.image = [UIImage imageNamed:#"iphone-4-apple-logo-wallpapers-set-2-05.jpg"];
[self.view addSubview:img];
NSLog(#"Height Pro %f",[[DeviceClass instance] getResizeScreen:NO].size.height);
scrollView = [[UIScrollView alloc] initWithFrame:[[DeviceClass instance] getResizeScreen:NO]];
scrollView.alwaysBounceVertical = YES;
scrollView.delegate = self;
[self.view addSubview:scrollView];
segmentControl = [[UISegmentedControl alloc] initWithItems:#[NSLocalizedString(#"profile_tab_signin", nil),NSLocalizedString(#"profile_tab_signup", nil)]];
segmentControl.frame = CGRectMake(10, 10, 300, 40);
segmentControl.selectedSegmentIndex = 0;
[segmentControl addTarget:self action:#selector(valueChanged) forControlEvents: UIControlEventValueChanged];
[scrollView addSubview:segmentControl];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleTap];
//Init
[self autoLogin];
[self.view setNeedsDisplay];
//[signUpBtn setBackgroundColor:[UIColor redColor]];
//[loginBtn setBackgroundColor:[UIColor yellowColor]];
}
- (void)valueChanged
{
//For SignIn/SignUp
if(segmentControl.selectedSegmentIndex == 0)
{
[usernameSignUp removeFromSuperview];
[emailSignUp removeFromSuperview];
[firstNameSignUp removeFromSuperview];
[lastNameSignUp removeFromSuperview];
[passwordSignUp removeFromSuperview];
[retypepasswordSignUp removeFromSuperview];
[signUpBtn removeFromSuperview];
//[signUpBtn setBackgroundColor:[UIColor redColor]];
[self signInForm];
}
else
{
[lostPassword removeFromSuperview];
[username removeFromSuperview];
[password removeFromSuperview];
[loginBtn removeFromSuperview];
[self signUpForm];
}
}
Please suggest me some useful code as I am new in iOS.

Programmatically Click 10 UIButtons one after another in UIScrollView

I am developing one control where 10 UIButtons are added in UIScrollView. Now I have a requirement to click every Button one after another after some delay. can you all guide me how to do that?
here is the code what I have done.
in viewcontroller.h file
#property (weak) IBOutlet UIScrollView *mapScrollView;
#property (strong) UIButton *addContactIcon;
in viewcontroller.m file
// Set up ScrollView with UIButtons
NSUInteger xPosition = 1;
NSUInteger countIndex = 0;
for (ContactModule *sortedContacts in _distanceList) {
_addContactIcon = [[UIButton alloc] initWithFrame:CGRectMake(xPosition, 7, 30, 30)];
_addContactIcon.tag = countIndex;
[_addContactIcon addTarget:self action:#selector(mapsScrollButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
_addContactIcon.layer.cornerRadius = 2.0;
_addContactIcon.clipsToBounds = YES;
[_addContactIcon setBackgroundImage:[UIImage imageWithContentsOfFile:dataPath] forState:UIControlStateNormal];
[_addContactIcon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_mapScrollView addSubview:_addContactIcon];
xPosition += _addContactIcon.frame.size.width + 2;
countIndex = countIndex + 1;
}
_mapScrollView.contentSize = CGSizeMake(30 * _distanceList.count + 34, 40);
[_mapScrollView setShowsHorizontalScrollIndicator:NO];
Here is the Button Click Method For Every Button:
- (void)mapsScrollButtonClicked:(UIButton *)clickButton {
// Set Annotation Callout
[_mapsView selectAnnotation:[_mapsView.annotations objectAtIndex:clickButton.tag] animated:YES];
}
Now the requirement is I want to call Action Method for Every UIButtons in UIScrollview. for that I am doing something wrong below. help me with that:
for(NSUInteger count=0; count<[_distanceList count];count++) {
[UIView animateWithDuration:0.4
delay:0.8
options:0
animations:^{
[_addContactIcon sendActionsForControlEvents:UIControlEventTouchUpInside];
} completion:nil];
}
Hi you could do soemthing like below to click all the UIButtons on your view.
UIButton *button;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *buttonMaster;
buttonMaster = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonMaster addTarget:self
action:#selector(masterButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
[buttonMaster setTitle:#"Show View" forState:UIControlStateNormal];
buttonMaster.frame = CGRectMake(80.0, y, 160.0, 40.0);
buttonMaster.tag = 100;
[self.view addSubview:buttonMaster];
y = 60;
for (int x=0; x<=10; x++)
{
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(button1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, y, 160.0, 30.0);
button.tag = x;
//[paintView addSubview:button];
[self.view addSubview:button];
y = y + 70;
}
[buttonMaster sendActionsForControlEvents:UIControlEventTouchUpInside];
if ([[self.view viewWithTag:0] isKindOfClass:[UIButton class]]) {
//UIButton *button = (UIButton *) view;
// do something funky with button
UIButton *myBtns = (UIButton *)[self.view viewWithTag:0];
NSLog(#" button tapped is %ld", myBtns.tag);
[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
[myBtns setBackgroundColor:[UIColor greenColor]];
} else {
// do something funky with view
NSLog(#"do nothing ");
}
}
- (void)listSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
// Return if there are no subviews
//if ([subviews count] == 0) return; // COUNT CHECK LINE
for (UIView *subview in subviews) {
UIButton *myBtns = (UIButton *)[self.view viewWithTag:subview.tag];
//UIButton *myBtns = (UIButton *)[self.view viewWithTag:0];
if(myBtns.tag == 100 ){
NSLog(#"Master Button tag :- Dont do anything ");
}else
{
//[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
NSLog(#"tags are %ld ", myBtns.tag);
}
// List the subviews of subview
//[self listSubviewsOfView:subview];
}
}
-(void) clickAllButtons{
for (int i = 0; i<=10; i++) {
UIButton *myBtns = (UIButton *)[self.view viewWithTag:i];
[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
}
}
- (IBAction)masterButtonTapped:(UIButton*)sender{
//[self listSubviewsOfView:self.view];
// [self clickAllButtons];
}
- (IBAction)button1:(UIButton*)sender{
NSLog(#"test");
//NSLog(#"Button clicked %ld", tag);
}

UIButton image does not show in Navigation Bar

I am trying to a slide menu. The only problem is that the image for the UIButton does not show at runtime. This is the code I have written.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(NSString *)segueIdentifierForIndexPathInLeftMenu:(NSIndexPath *)indexPath
{
NSString *identifier;
switch (indexPath.row) {
case 0:
identifier=#"firstSegue";
break;
case 1:
identifier=#"secondSegue";
break;
}
return identifier;
}
-(void)configureLeftMenuButton:(UIButton *)button
{
CGRect frame = button.frame;
frame.origin=(CGPoint){0.0};
frame.size = (CGSize){40.40};
button.frame = frame;
[button setImage:[UIImage imageNamed:#"icon-menu"] forState:UIControlStateNormal];
}
I suppose you are using navigation controller. If so, implementation could look like:
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureLeftMenuButton];
}
-(void)configureLeftMenuButton
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"icon-menu"] forState:UIControlStateNormal];
button.frame = CGRectMake(0.0f, 0.0f, 44.0f, 44.0f);
[button addTarget:self
action:#selector(yourAction:)
forControlEvents:UIControlStateNormal];
UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = menuItem;
}

How to achieve fixed side navigation in iOS?

I am new to iOS development. I am developing an app which will contain fixed side menu on left side of all ViewController. When user will select any menu out of 5, selected menu will highlighted in different colour, but its later part.
How do I achieve the fixed side menu?
I am stuck on this. I search so many sites on Google but nothing helpful came out of it. Can anyone provide sample code?
Any help would be appreciated.
Thanks & Regards.
Please try this code.
First create a UIView type class.
Write this code TabbarController.h Class
#import <UIKit/UIKit.h>
#class TabbarController;
#protocol Tabbar_protocol <NSObject>
#required
-(void)First_viewController;
-(void)Second_viewController;
-(void)Third_viewController;
-(void)Fourth_viewController;
-(void)Fifth_viewController;
#end
#interface TabbarController : UIView // this is your UIView type class
-(void)CreateTabbarController;
#property (nonatomic, assign) NSObject <Tabbar_protocol> *delegate;
#end
This code for TabbarController.m Class
#import "TabbarController.h"
#implementation TabbarController
#synthesize delegate;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self CreateTabbarController];
}
return self;
}
-(void)CreateTabbarController
{
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setFrame:CGRectMake(0, 0, 50, 96)];
[button1 setBackgroundImage:[UIImage imageNamed:#"image1.png"] forState:UIControlStateNormal];
[button1 setTag:101];
[button1 addTarget:self action:#selector(TabbarBtn_Action:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setFrame:CGRectMake(0, 96, 50, 96)];
[button2 setBackgroundImage:[UIImage imageNamed:#"image2.png"] forState:UIControlStateNormal];
[button2 setTag:102];
[button2 addTarget:self action:#selector(TabbarBtn_Action:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button2];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 setFrame:CGRectMake(0, 192, 50, 96)];
[button3 setBackgroundImage:[UIImage imageNamed:#"image3.png"] forState:UIControlStateNormal];
[button3 setTag:103];
[button3 addTarget:self action:#selector(TabbarBtn_Action:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button3];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 setFrame:CGRectMake(0, 288, 50, 96)];
[button4 setBackgroundImage:[UIImage imageNamed:#"image4.png"] forState:UIControlStateNormal];
[button4 setTag:104];
[button4 addTarget:self action:#selector(TabbarBtn_Action:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button4];
UIButton *button5 = [UIButton buttonWithType:UIButtonTypeCustom];
[button5 setFrame:CGRectMake(0, 384, 50, 96)];
[button5 setBackgroundImage:[UIImage imageNamed:#"image5.png"] forState:UIControlStateNormal];
[button5 setTag:105];
[button5 addTarget:self action:#selector(TabbarBtn_Action:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button5];
}
-(void)TabbarBtn_Action:(id)sender
{
switch ([sender tag])
{
case 101:
if (self.delegate != nil)
{
// code for changing your button color
[self.delegate First_viewController];
}
break;
case 102:
if (self.delegate != nil)
{
// code for changing your button color
[self.delegate Second_viewController];
}
break;
case 103:
if (self.delegate != nil)
{
// code for changing your button color
[self.delegate Third_viewController];
}
break;
case 104:
if (self.delegate != nil)
{
// code for changing your button color
[self.delegate Fourth_viewController];
}
break;
case 105:
if (self.delegate != nil)
{
// code for changing your button color
[self.delegate Fifth_viewController];
}
break;
default:
break;
}
}
#end
In your all ViewController.h import this class & ViewController.m class call that delegate method.
#import "TabbarController.h"
#interface ViewController : UIViewController <Tabbar_protocol>
{
}
// ViewController.m class
-(void)First_viewController
{
// Navigate to FirstViewController...
}
-(void)Second_viewController
{
// Navigate to SecondViewController...
}
-(void)Third_viewController
{
// Navigate to ThirdViewController...
}
-(void)Fourth_viewController
{
// Navigate to FourthViewController...
}
-(void)Fifth_viewController
{
// Navigate to FifthViewController...
}
Like this you have to call in all 5 ViewController.

Resources