I'm new to ios and Objective-C. Please be a little bit patient with me.
THe functionality in my app, which I'm trying to develop, is a small scrolling toolbar, which contains several buttons, state toggling buttons. Also there is another button above the toolbar which slides in and out the toolbar. The second functionality I achieved successfully, using a view for the whole setup and when the slide button touch up event animates the whole view up and down.
For the scrollview, I wanted to add buttons programmatically, hence I drew an outlet to the class and tried adding a self created button as a subview. However I cannot see the button. Nor can I observe the scrollview sliding.
THe following is the way I'm adding the button:
Also, my total view for the above functionality is very less in size than the total view controller
UIButton *button = [[UIButton alloc] init];
button.titleLabel.text = #"hello";
[_scrollTop setContentSize:self.view.frame.size];
[_scrollTop addSubview:button];
The two images down, I hope, should help you understand the functionality I'm trying to develop. If anybody is aware of existence of similar functionality, please do direct me.
Edit: Code totally is
//
// HCILocationViewController.m
// app2
//
// Created by Ravi Vooda on 13/03/13.
// Copyright (c) 2013 housing.co.in. All rights reserved.
//
#import "HCILocationViewController.h"
#import "HCIAnnotationViewController.h"
#interface HCILocationViewController ()
#property int widMap;
#property BOOL showExploreOptions;
#end
#implementation HCILocationViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_mapLocationView.delegate = self;
MKPointAnnotation *annotation = [[HCIAnnotationViewController alloc]
initwithHouse:[self singleHome]];
[_mapLocationView addAnnotation:annotation];
_widMap = 10000;
_showExploreOptions = NO;
/*
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);//give values whatever you want.
[_scrollTop addSubview:button];
*/
[self addButtonsToScrollView];
}
- (void)addButtonsToScrollView
{
NSInteger buttonCount = 4;
CGRect buttonFrame = CGRectMake(5.0f, 5.0f, self.scrollTop.frame.size.width-10.0f, 40.0f);
for (int index = 0; index <buttonCount; index++) {
UIButton *button = [[UIButton alloc]initWithFrame:buttonFrame];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:index+1];
NSString *title = [NSString stringWithFormat:#"Button %d",index+1];
[button setTitle:title forState:UIControlStateNormal];
[self.scrollTop addSubview:button];
buttonFrame.origin.y+=buttonFrame.size.height+5.0f;
}
CGSize contentSize = self.scrollTop.frame.size;
contentSize.height = buttonFrame.origin.y;
[self.scrollTop setContentSize:contentSize];
}
- (void)buttonPressed:(UIButton *)button
{
NSLog(#"button pressed");
switch (button.tag) {
case 1:
//Do something
break;
default:
break;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(MKAnnotationView*) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
NSString *identifier = #"currDetailsIdentifier";
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[_mapLocationView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation
reuseIdentifier:identifier];
} else {
annotationView.annotation = annotation;
}
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
return annotationView;
}
-(void) mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
MKMapRect zoomRect = MKMapRectNull;
for (id <MKAnnotation> annotation in mapView.annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(
annotationPoint.x - (_widMap / 2),
annotationPoint.y - (_widMap/2),
_widMap,
_widMap);
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect;
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
}
[mapView setVisibleMapRect:zoomRect animated:YES];
}
-(void) setMyHouse:(NSDictionary *)singleHouse {
self.singleHome = singleHouse;
}
- (IBAction)toggleExploreOptionsView:(UIButton *)sender {
sender.selected = !sender.selected;
if (_showExploreOptions){
NSLog(#"Close Options");
[UIView animateWithDuration:0.2 animations:^{
_exploreView.frame = CGRectMake(_exploreView.frame.origin.x, _exploreView.frame.origin.y + _exploreOptionsView.frame.size.height, _exploreView.frame.size.width, _exploreView.frame.size.height + _exploreOptionsView.frame.size.height);
}];
}
else {
NSLog(#"Open Options");
[UIView animateWithDuration:0.2 animations:^{
_exploreView.frame = CGRectMake(_exploreView.frame.origin.x, _exploreView.frame.origin.y - _exploreOptionsView.frame.size.height, _exploreView.frame.size.width, _exploreView.frame.size.height - _exploreOptionsView.frame.size.height);
}];
}
_showExploreOptions = !_showExploreOptions;
}
#end
If I understood your question correctly you need to have view which should show up and collapse on a button click event. When the view is shown, it should have a scrollable list of buttons. And you are asking help to show many buttons to scrollView.
Demo Source Code
- (void)addButtonsToScrollView
{
NSInteger buttonCount = 5;
CGRect buttonFrame = CGRectMake(5.0f, 5.0f, self.scrollTop.frame.size.width-10.0f, 40.0f);
for (int index = 0; index <buttonCount; index++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:buttonFrame];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:index+1];
NSString *title = [NSString stringWithFormat:#"Button %d",index+1];
[button setTitle:title forState:UIControlStateNormal];
[self.scrollTop addSubview:button];
buttonFrame.origin.y+=buttonFrame.size.height+5.0f;
}
CGSize contentSize = self.scrollTop.frame.size;
contentSize.height = buttonFrame.origin.y;
[self.scrollTop setContentSize:contentSize];
}
- (void)buttonPressed:(UIButton *)button
{
switch (button.tag) {
case 1:
//Do something
break;
default:
break;
}
}
Related
I have a UIButton inside a UIView, when the UIButton is selected I would like have a background colour of dark gray...is this possible?
UIView *toolbar = [[UIView alloc]initWithFrame:CGRectMake(10, 50, 40, 160)];
[toolbar setBackgroundColor:[UIColor colorWithWhite: 0.70 alpha:0.5]];
toolbar.layer.cornerRadius = 5;
UIButton *penTool = [UIButton buttonWithType:UIButtonTypeCustom];
penTool.frame = CGRectMake(5, 0, 30, 30);
[penTool setImage:[UIImage imageNamed:#"pen-but" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
[penTool addTarget:self action:#selector(drawButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
penTool.autoresizingMask = UIViewAutoresizingNone;
penTool.exclusiveTouch = YES;
penTool.tag = 1;
[toolbar addSubview:penTool];
What if you can do this?
[button setBackgroundColor:[UIColor greenColor]
forState:UIControlStateSelected];
Let's give a great API for every state, not just selected, just like UIButton default API's ability to change image and title for every state.
BGButton.h
#import <UIKit/UIKit.h>
#interface BGButton : UIButton
- (void)setBackgroundColor:(UIColor *)backgroundColor
forState:(UIControlState)state;
#end
BGButton.m
#import "BGButton.h"
#implementation BGButton {
NSMutableDictionary *_stateBackgroundColor;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_stateBackgroundColor = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
[super setBackgroundColor:backgroundColor];
/*
* If user set button.backgroundColor we will set it to
* normal state's backgroundColor.
* Check if state is on normal state to prevent background being
* changed for incorrect state when updateBackgroundColor method is called.
*/
if (self.state == UIControlStateNormal) {
[self setBackgroundColor:backgroundColor forState:UIControlStateNormal];
}
}
- (void)setBackgroundColor:(UIColor *)backgroundColor
forState:(UIControlState)state {
NSNumber *key = [NSNumber numberWithInt:state];
[_stateBackgroundColor setObject:backgroundColor forKey:key];
}
/*
* state is synthesized from other flags. So we can't use KVO
* to listen for state changes.
*/
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
[self stateDidChange];
}
- (void)setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
[self stateDidChange];
}
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
[self stateDidChange];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self stateDidChange];
}
- (void)stateDidChange {
[self updateBackgroundColor];
}
- (void)updateBackgroundColor {
NSNumber *key = [NSNumber numberWithInt:self.state];
self.backgroundColor = [_stateBackgroundColor objectForKey:key];
}
#end
You can use it like the default UIButton API
BGButton *button = [[BGButton alloc] init];
[button setBackgroundColor:[UIColor greenColor]
forState:UIControlStateSelected];
[button setBackgroundColor:[UIColor blueColor]
forState:UIControlStateHighlighted];
[button setBackgroundColor:[UIColor orangeColor]
forState:UIControlStateDisabled];
Even if you use
button.backgroundColor = [UIColor redColor];
You will stay safe, it will be translated into
[button setBackgroundColor:[UIColor redColor]
forState:UIControlStateNormal];
if you have this code
[self.view addSubview:toolbar];
then just implement your button selector
-(void)drawButtonTapped:(UIButton*)button{
if (button.selected) {
button.backgroundColor = [UIColor clearColor];
button.selected = NO;
}else{
button.backgroundColor = [UIColor darkGrayColor];
button.selected = YES;
}
}
I don't know why guys would go through such trouble when we have this functionality built-in inside UIButton. All you need to do is use UIButtonTypeSystem That's all.
[UIButton buttonWithType:UIButtonTypeSystem]
Seriously, there's nothing more to it. Have a look at it's behavior in the screenshots.
INTERFACE BUILDER
RUN TIME
Want to change color, set tintColor to color of your choice.
ADVANTAGES
Covers titles with dynamic lengths. Not applied on all button width.
When selected, title color is transparent, your background can be seen through, try to use an image as a background.
Let's hope you have at least iOS7 as deployment target. UIButtonTypeSystem was introduce with revised UI design guidelines of iOS7 and has been there for almost 3 years.
Good Luck!
I used a UIButton subclass here:
#import "CustomButton.h"
#interface CustomButton()
#property (nonatomic,strong) UIColor *originalColor;
#end
#implementation CustomButton
- (void)didMoveToSuperview
{
self.originalColor = self.superview.backgroundColor;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.superview.backgroundColor = [UIColor grayColor];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
if ([self hitTest:location withEvent:nil]) {
self.superview.backgroundColor = [UIColor grayColor];
self.originalColor = self.superview.backgroundColor;
}
else
{
self.superview.backgroundColor = self.originalColor;
}
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.superview.backgroundColor = self.originalColor;
}
#end
If you subclass your button from this class, It should give you the desired effect. This also gives you the highlight effect. If you wish you can disable it by removing the line on touchesBegan.
Just try to Override the UIButton with the following Method...
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = [UIColor darkGray];
}
}
I think you'll be want to change the selectedImage for flexibility not the background.
Add another image (e.g. pen-but-selected) in the project. Add this 2nd line for setImage:
[penTool setImage:[UIImage imageNamed:#"pen-but-selected" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateSelected];
- (void)drawButtonTapped:(UIButton *)button {
button.selected = !button.selected;
}
If you still want to change background color. #jamil's answer would work. Make sure the buttonImage has transparent part so you can see the buttonBackground through the buttonImage.
Try using a boolean, or some other reference to the selection state of the button. You could also make use of a 'highlightColour' as well as the 'selectedColour' if you wanted closer control (should probably do this for better UX).
bool buttonIsSelected = false;
UIColor * selectedColour = [UIColor redColor];
UIColor * defaultColour = [UIColor blueColor];
UIButton * button = [UIButton new];
button.frame = CGRectMake(0,0,100,100);
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
[button addTarget:self action:#selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:#selector(buttonTouchCancel:) forControlEvents:UIControlEventTouchCancel];
[button addTarget:self action:#selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
-(void)buttonTouchUp:(UIButton *)button {
if (buttonIsSelected){
buttonIsSelected = false;
button.backgroundColor = defaultColour;
} else {
buttonIsSelected = true;
button.backgroundColor = selectedColour;
}
}
-(void)buttonTouchCancel:(UIButton *)button {
button.backgroundColor = defaultColour;
if (buttonIsSelected){
button.backgroundColor = selectedColour;
}
}
-(void)buttonTouchDown:(UIButton *)button {
button.backgroundColor = selectedColour;
}
-(void)OnSelect:(UIButton*)button{
if (button.selected) {
button.backgroundColor = [UIColor blue];
button.selected = NO;
}else{
button.backgroundColor = [UIColor darkGrayColor];
button.selected = YES;
}
}
use the above this will work..
-(void)buttonTapped:(UIButton*)button{
button.selected =! button.selected;
if (button.selected)
button.backgroundColor = [UIColor grayColor];
else
button.backgroundColor = [UIColor clearColor];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MKAnnotationView *view = [self.mapView dequeueReusableAnnotationViewWithIdentifier:#"loc"];
return view;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
for (MKAnnotationView *annotationView in views) {
annotationView.canShowCallout = NO;
}
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
MAKRCalloutView *calloutView = [[MAKRCalloutView alloc] initWithNibName:#"ViewM" bundle:nil];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10.0, 10.0, 50.0, 50.0)];
[btn setBackgroundColor:[UIColor redColor]];
[btn addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:calloutView.view];
[view addSubview:btn];
}
-(void) buttonClicked:(id)sender{
NSLog(#" %ld button click %# ", (long)[sender tag]);
}
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
for (UIView *subview in view.subviews) {
MAKRCalloutView *calloutView = [[MAKRCalloutView alloc] initWithNibName:#"ViewM" bundle:nil];
if (![subview isKindOfClass:[calloutView.view class]]) {
continue;
}
[subview removeFromSuperview];
}
}
I cannot call get button click event. Even I cannot click on button also. I want to go at other UIViewController by click on button.
I have also tried UITapGestureRecognizer. But its limited to Pin area only.
[button addTarget:self action:#selector(clickEvent) forControlEvents:UIControlEventTouchDown]
And then
- (CustomAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[CustomAnnotation class]])
{
CustomAnnotationView *newAnnotationView = nil;
// determine the type of annotation, and produce the correct type of annotation view for it.
newAnnotationView = [[[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil delegate: targetController] autorelease];
[newAnnotationView setEnabled:YES];
[newAnnotationView setCanShowCallout:NO];
return newAnnotationView;
}
}
#interface CustomAnnotationView : MKAnnotationView
{
}
#end
#implementation CustomAnnotationView
- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier delegate:(id)targetController
{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
/* Set initial width as you want. ex: 50X50*/
self.frame = CGRectMake(0, 0, Initial_width, Initial_height);
self.backgroundColor = [UIColor redColor];
return self;
}
/* When you tap on an annotation this method is fired*/
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
if(selected){
/* When you select annotation, instead of showing default callout you can increase the width &height of annotation and add your custom view here*/
self.frame = CGRectMake(0, 0, max_width, max_height);
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(6, 0, max_width-10, max_height)];
view.backgroundColor = [UIColor blackColor];
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:#"image.png"];
but = CGRectMake(x , y, img.size.width + 20, img.size.height + 15);
[but setImage:img forState:UIControlStateNormal];
[but addTarget:targetController action:#selector(methodName) forControlEvents:UIControlEventTouchDown];
[view addSubview:but];
[self addSubview:view];
}
else {
/* When you tap outside of annotation, set the initial frame for the annotation. and remove the custom view from annotation*/
self.frame = CGRectMake(0, 0, Initial_width, Initial_height);
[view removeFromSuperview];
}
}
I have simple app with Map and pins attached to it. After clicking on pin on map, pinView is created, on wchich I have button with action called let's say ButtonPressed.
I want to know from which pin it was pressed. I tried something like :
(IBAction)ButtonPressed:(id)sender
{
UIButton *but = (UIButton*) sender;
NSLog(#"SEG PLZ SEG CMON %tu",but.superview.tag);
[self performSegueWithIdentifier:#"segu" sender:sender];
}
But it always returns 0, no matter that I set tag for 5.
Okay I post code for adding buttons as you wanted :
- (MKPinAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)myannotation{
MKPinAnnotationView *view = nil;
//MKPinAnnotationView *view=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"HotSpotsLoc"];
if(myannotation !=mapView.userLocation){
view = (MKPinAnnotationView *)
[mapView dequeueReusableAnnotationViewWithIdentifier:#"identifier"];
if(nil == view) {
view = [[MKPinAnnotationView alloc]
initWithAnnotation:myannotation reuseIdentifier:#"identifier"];
}
UIButton *btnViewVenue = [UIButton buttonWithType:UIButtonTypeContactAdd];
[view.rightCalloutAccessoryView setTag:50];
[btnViewVenue addTarget:self action:#selector(ButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
view.rightCalloutAccessoryView=btnViewVenue;
view.enabled = YES;
view.pinColor = MKPinAnnotationColorPurple;
view.canShowCallout = YES;
view.multipleTouchEnabled = NO;
//view.animatesDrop = YES;
UIButton *btnViewwVenue = [UIButton buttonWithType:UIButtonTypeContactAdd ] ;
[btnViewwVenue addTarget:self action:#selector(addImage:) forControlEvents:UIControlEventTouchUpInside];
[view setTag:50];
view.leftCalloutAccessoryView=btnViewwVenue;
view.enabled = YES;
view.pinColor = MKPinAnnotationColorPurple;
view.canShowCallout = YES;
view.multipleTouchEnabled = NO;
}
return view;
}
Setting leftCalloutAccessoryView and rightCalloutAccessoryView does not necessarily add the views as subviews of view. If you need this relationship to be explicit, consider subclassing UIButton.
#interface MyButton : UIButton
#property (weak) MKPinAnnotationView *annotation;
#end
#implementation MyButton
#end
// Then...
(IBAction)ButtonPressed:(id)sender
{
MyButton *but = (MyButton*) sender;
NSLog(#"SEG PLZ SEG CMON %tu",but.annotation.tag);
[self performSegueWithIdentifier:#"segu" sender:sender];
}
Hi my requirement is showing image in scrollview along with that it should display next and previous button.User can scroll the image as well as use buttons to move images.
I have doubt about how to get the index/tag/imagename or anything else when user scroll based on that values buttons should be updated.
Here is my Code
[self arrayInitiaisation];
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical = NO;
scrollview.alwaysBounceHorizontal = YES;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"image%d",i+1]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag = i;
...
Array Initialisation method
-(void) arrayInitialisation {
count=0;
[super viewDidLoad];
images=[NSMutableArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
Action Methods
- (IBAction)nextButton:(id)sender {}
- (IBAction)prevButton:(id)sender {}
scroll is working correctly but when user clicks on prev and next image is not updating on 'imageview'
Here is my updated code
int count=0;
- (void)viewDidLoad
{
[super viewDidLoad];
[self arrayInitialisation];
[scrollview setScrollEnabled:YES];
self.scrollview =[[UIScrollView alloc] initWithFrame:CGRectMake(30 , 30, 320, 412)];
self.scrollview.delegate=self;
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical=NO;
scrollview.alwaysBounceHorizontal=YES;
scrollview.showsHorizontalScrollIndicator=NO;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(xOrigin, 0, 320, 412)];
imageView.image = [images objectAtIndex:i];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag=i;
}
scrollview.contentSize = CGSizeMake(320*numberOfViews, 412);
scrollview.contentOffset = CGPointMake(0,0);
[self.view addSubview:self.scrollview];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void) arrayInitialisation{
count=0;
[super viewDidLoad];
images=[NSArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
- (IBAction)nextButton:(id)sender {
if(count==0){
count++;
NSLog(#"Next Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
}
else{
[previous setEnabled:YES];
count++;
NSLog(#"Next Button : else Loop %d",count);
if(count <images.count){
[imageView setImage:[images objectAtIndex:count]];
}
else{
[next setEnabled:NO];
}
}
}
- (IBAction)prevButton:(id)sender {
if(count==0){
//count--;
NSLog(#"prev Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:NO];
[next setEnabled:YES];
}
else{
count--;
NSLog(#"prev Button : else Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
//[next setEnabled:YES];
}
}
#pragma mark - ScrollView Delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate: (BOOL)decelerate{
//NSLog(#"scrollViewDidEndDragging");
/* count=count+1;
NSLog(#"scrollViewDidEndDragging : %d",count);*/
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//NSLog(#"scrollViewDidScroll");
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0){
//NSLog(#"scrollViewWillEndDragging");
count=count+1;
NSLog(#"scrollViewWillEndDragging : %d",count);
}
I have left and right button for scroll images, and imageview width is same.
I am writing code for scroll image at pressing button.
int pos=0;// ViewDiaLoad
- (IBAction)OnClickLeftButton:(UIButton*)sender
{
if(pos>0)
{
pos -=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
- (IBAction)OnClickRightButton:(UIButton*)sender
{
if(pos<numberOfImages)
{
pos +=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
Set scrollView Deleagte
Scroll View delegate Method
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
pos=scrollView.contentOffset.x/scrollView.frame.size.width;
}
You can use UIPageControl and set and get image according to page index. For more information check out this link
Try below piece of code. I hope it will help. Put this in your .h file
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
NSMutableArray *arrImages;
NSInteger page;
Now in your - (void)viewDidLoad put following lines.
int x = 30;
for (int i=0; i< arrImages.count; i++)
{
UIImageView *imgShow = [[UIImageView alloc]initWithFrame:CGRectMake(x+20, 50, self.view.frame.size.width-100, self.view.frame.size.height-180)];
imgShow.backgroundColor = [UIColor whiteColor];
imgShow.image = [UIImage imageNamed:[arrImages objectAtIndex:i]];
imgShow.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview:imgShow];
x = x+scrollView.frame.size.width;
}
scrollView.contentSize = CGSizeMake(5*self.view.frame.size.width, 0);
pageControl.backgroundColor = [UIColor clearColor];
pageControl.pageIndicatorTintColor = [UIColor grayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
[pageControl setTintAdjustmentMode:UIViewTintAdjustmentModeDimmed];
pageControl.numberOfPages = arrTitle.count;
pageControl.currentPage = 0;
implement scroll view delegate.
#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1
{
CGFloat pageWidth = scrollView.frame.size.width;
float fractionalPage = scrollView.contentOffset.x / pageWidth;
page = lround(fractionalPage);
pageControl.currentPage = page;
}
- (IBAction)prevButton:(UIButton *)sender
{
page = page-1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
- (IBAction)nextButton:(UIButton *)sender
{
page = page+1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
I currently have two buttons in my SearchCategoryChooserViewController. What I want to do is to set the chosenCategory property to a certain value depending on which button is pressed, and then send that value over to CriteriaViewController.
I have some psuedo code commented out in my categoryButtonClick function, but I'm not sure how to format the syntax, and where to take it from there. The topCategoryId1 and topCategoryId2 values are coming from SearchViewController. Let me know if you want me to include code from that or any other classes.
SearchCategoryChooserViewController.m:
#import "SearchCategoryChooserViewController.h"
#import "SearchViewController.h"
#import "CriteriaViewController.h"
#interface SearchCategoryChooserViewController ()
#end
#implementation SearchCategoryChooserViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *category1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
category1.frame = CGRectMake(10, 120, 300, 35);
[category1 setTitle: [NSString stringWithFormat:#"%#", self.topCategory1] forState:UIControlStateNormal];
[category1 addTarget:self action:#selector(categoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: category1];
UIButton *category2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
category2.frame = CGRectMake(10, 180, 300, 35);
[category2 setTitle: [NSString stringWithFormat:#"%#", self.topCategory2] forState:UIControlStateNormal];
[category2 addTarget:self action:#selector(categoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: category2];
}
- (IBAction)categoryButtonClick:(id)sender
{
// if (topCategory1 button is pressed) {
// set chosenCategory = self.topCategoryId1
// }
//
// else if (topCategory2 button is pressed) {
// set chosenCategory = self.topCategoryId2
// }
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
// Send the Category Id over to CriteriaViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
CriteriaViewController *controller = (CriteriaViewController *) segue.destinationViewController;
// Send over the search query as well as the specific category to CriteriaVC to use
controller.chosenCategory = self.topCategoryId1;
}
#end
One possible solution would be to use tags. Set each button to have its own tag after creating it, for example:
UIButton *category1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
category1.frame = CGRectMake(10, 120, 300, 35);
[category1 setTitle: [NSString stringWithFormat:#"%#", self.topCategory1] forState:UIControlStateNormal];
[category1 addTarget:self action:#selector(categoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
category1.tag = 1; //added tag to button
[self.view addSubview: category1];
UIButton *category2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
category2.frame = CGRectMake(10, 180, 300, 35);
[category2 setTitle: [NSString stringWithFormat:#"%#", self.topCategory2] forState:UIControlStateNormal];
[category2 addTarget:self action:#selector(categoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
category2.tag = 2; //added tag to button
[self.view addSubview: category2];
Then in your button action method (categoryButtonClick:), check the button's tag like so:
- (IBAction)categoryButtonClick:(id)sender
{ UIButton *button = (UIButton *)sender;
if(button.tag == 1){
chosenCategory = self.topCategoryId1;
}else{
chosenCategory = self.topCategoryId2;
}
}
You could do:
- (IBAction)categoryButtonClick:(id)sender
{
if ([topCategory1 isSelected]) {
set chosenCategory = self.topCategoryId1
}
else if ([topCategory2 isSelected]) {
set chosenCategory = self.topCategoryId2;
}
}
In adition to the #croberth's answer, after conditionally setting chosenCategory, send a performSegueWithIdentifier:sender: message:
- (IBAction)categoryButtonClick:(id)sender
{
UIButton *button = (UIButton *)sender;
if(button.tag == 1) {
chosenCategory = self.topCategoryId1;
}
else {
chosenCategory = self.topCategoryId2;
}
[self performSegueWithIdentifier:#"YOUR_SEGUE_IDENTIFIER" sender:nil];
}
YOUR_SEGUE_IDENTIFIER is the identifier for your segue between the button and the CriteriaViewController. Since your buttons aren't in your storyboard, it should be a segue between the 2 controllers, not from any button.
What you're asking has been answered several times already on SO. You set up a variable in the sending VC in the prepareForSegue method and prepare a variable to receive that value in the receiving VC. Here's an SO link with a lot more detail: ios pass values during a segue to another view