I have programmatically generated UIButtons that all share the same selector method. When the method runs I would like the method to know which button was pressed and then be able to load a corresponding UIViewController.
-(void)buildButtons
{
for( int i = 0; i < 5; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:i];
[aButton addTarget:self action:#selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
Then:
- (void)buttonClicked:(UIButton*)button
{
NSLog(#"Button %ld clicked.", (long int)[button tag]);
// code here that picks the correct viewController to push to...
// for example tag 1 would create an instance of vcTwo.m and would then be pushed to the navigationController and be displayed on screen
}
say I have three UIViewController classes (vcOne.m, vcTwo.m, vcThree.m) and I want it so that when the button is pressed 'buttonClicked' is run and the code picks the corresponding viewController to push to. I don't want to use a series of if statements as there may be dozens/hundreds of viewControllers in the end. Would I have to instantiate all of the viewControllers and put them in an array? Is there a better way?
Are you using storyboards? so you can chose a segue according to the button tag:
int i = (int)[button tag];
[self performSegueWithIdentifier:[NSString stringWithFormat:#"Segue%d", i] sender:self];
or:
UIViewController *viewController= [controller.storyboard instantiateViewControllerWithIdentifier:NSString stringWithFormat:#"ViewControllerNumber%d", i];
In the end I went with this:
- (void) buttonClicked:(id)sender
{
NSLog(#"Button tag = %li", (long)[sender tag]);
FormularyVC *formularyVCInstance = [FormularyVC alloc];
ProceduresVC *proceduresVCInstance = [ProceduresVC alloc];
VetMedVC *vetMedVCInstance = [VetMedVC alloc];
NSArray *vcArray = [NSArray arrayWithObjects:formularyVCInstance, proceduresVCInstance, vetMedVCInstance, nil];
UIViewController *vcToLoad = [vcArray objectAtIndex:(int)[sender tag]];
vcToLoad.view.backgroundColor = [UIColor whiteColor];
[self.navigationController pushViewController:vcToLoad animated:NO];
}
I created an array of the ViewControllers I wanted to be able to load based on which button was pressed. When the button is pressed the method is run and the tag is taken as a parameter. This tag is used to find the ViewController needed by checking its location on the array's index.
Related
I have a UIViewController with a bunch of buttons that each have a (unique) tag. I wrote the following method:
- (void) highlightButtonWithTag: (NSInteger) tag
{
UIButton *btn = (UIButton *)[self.view viewWithTag: tag];
btn.highlighted = YES;
}
What I am trying to do is have a bunch of buttons that each function like a toggle: when I tap one, it should be come active (i.e. highlighted) and the one that was highlighted before should become "un"highlighted.
When the view comes up, I use the viewDidAppear method to set the initial selection:
- (void) viewDidAppear:(BOOL)animated
{
self.selectedIcon = 1;
[self highlightButtonWithTag: self.selectedIcon];
}
And this seems to work just fine: when the view comes up, the first button is selected. However, when I try to update stuff through the #selector connected to the buttons, the previous button is "un"highlighted but the button with sender.tag doesn't get highlighted.
- (IBAction) selectIcon:(UIButton *)sender
{
// "Un"highlight previous button
UIButton *prevButton = (UIButton *)[self.view viewWithTag: self.selectedIcon];
prevButton.highlighted = NO;
// Highlight tapped button:
self.selectedIcon = sender.tag;
[self highlightButtonWithTag: self.selectedIcon];
}
What am I missing here?
The problem is that the system automatically highlights then unhighlights the button on touchDown and touchUp respectively. So, you need to highlight the button again, after it's unhighlighted by the system. You can do by using performSelector:withObject:afterDelay: even with a 0 delay (because the selector is scheduled on the run loop which happens after the system has done it's unhighlighting). To use that method, you have to pass an object (not an integer), so If you modify your code slightly to use NSNumbers, it would look like this,
- (void) highlightButtonWithTag:(NSNumber *) tag {
UIButton *btn = (UIButton *)[self.view viewWithTag:tag.integerValue];
btn.highlighted = YES;
}
- (void) viewDidAppear:(BOOL)animated {
self.selectedIcon = 1;
[self highlightButtonWithTag: #(self.selectedIcon)];
}
- (IBAction) selectIcon:(UIButton *)sender {
// "Un"highlight previous button
UIButton *prevButton = (UIButton *)[self.view viewWithTag: self.selectedIcon];
prevButton.highlighted = NO;
// Highlight tapped button:
self.selectedIcon = sender.tag;
[self performSelector:#selector(highlightButtonWithTag:) withObject:#(self.selectedIcon) afterDelay:0];
}
I started writing a project without really using the storyboard (as i was following a tutorial about creating an options menu for a game).
So i am trying to retroactively implement a way of moving between 2 UIViewControllers (MainGame and MatchScreen) that each has a UIView (MainMenu and VSComputer respectively).
Now in the MainMenu UIView I have created 4 buttons, with all their positions and settings, two of which are subviews - options and stats - that so appear and disappear when clicked on the current ViewController.
Now, the problem is, I need to somehow move from the main menu to the match screen using one of the other buttons named 'matchScreen'. I feel there must be something that i'm missing as no answer found in my research has worked for me yet.
I have embedded my main UIViewController with a navController (as suggested in other questions that i've seen) and then added a push segue to the 2nd ViewController. But i don't know how to make this apparent to my code. My code recognises nothing that i do in the storyboard it seems.
#interface JDTHMainMenu(){
JDTHOptionsScreen *theOptionScreen;
JDTHPlayerStats *thePlayerStatsScreen;
UIButton *optionScreenButton;
UIButton *matchScreenButton;
UIButton *deckScreenButton;
UIButton *statsScreenButton;
bool isPhone;
bool isOptionScreenOpen;
bool isPlayerStatsScreenOpen;
bool matchScreenButtonPressed;
UIView *tint;
int screenWidth;
int screenHeight;
AppData *appData;
}
So to be clear, JDTHMainMenu is a UIView in the JDTHViewController - the original, JDTHMatchScreen is the second ViewController and there is a UIView called JDTHVersusScreen. Im trying to go from one to the other. Also the JDTHAppDelegate only has return YES in the didFinishLaunching method. I feel i'm getting closer....but perhaps not...
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
appData = [AppData sharedData];
NSLog(#"Main Menu has loaded");
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
isPhone = YES;
} else {
isPhone = NO;
}
screenWidth = self.frame.size.width;
screenHeight = self.frame.size.height;
isOptionScreenOpen = NO;
isPlayerStatsScreenOpen = NO;
matchScreenButtonPressed = NO;
[self showOptionScreenButton];
[self showPlayerStatsScreenButton];
[self matchViewControllerButton:matchScreenButton];
[self deckViewerControllerButton:deckScreenButton];
}
return self;
}
-(IBAction)matchViewControllerButton:(UIButton *)sender{
CGRect rect;
UIFont *theFont;
if (isPhone == YES) {
rect = CGRectMake(38, 150, 134, 116);
theFont = [UIFont fontWithName:#"Zapfino" size:22];
} else {
rect = CGRectMake(275, 600, 200, 150);
theFont = [UIFont fontWithName:#"Zapfino" size:28];
}
matchScreenButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[matchScreenButton addTarget:self action:#selector(goToMatchView:sender:) forControlEvents:UIControlEventTouchDown];
[matchScreenButton.titleLabel setFont:theFont];
[matchScreenButton setTitle:#"VS Comp" forState:UIControlStateNormal];
matchScreenButton.frame = rect;
[matchScreenButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[matchScreenButton setBackgroundImage:[UIImage imageNamed:#"MainMenuOptionButton"] forState:UIControlStateNormal];
[self addSubview:matchScreenButton];
}
-(void)goToMatchView:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"pushToMatchView"]) {
JDTHMatchScreen *vc2 = (JDTHMatchScreen *)segue.destinationViewController;
vc2.name = self.textField.text;
}
}
A storyboard app has an entry in the info.plist file that tells the app that it's a storyboard app, and what the name of the storyboard is ("Main storyboard file base name" is the name of the key, and the value is the file name, without extension, of your storyboard). You would need to add this to your project to get it to recognize the storyboard. Also, non-storyboard apps usually have code in the app delegate to set up the initial controllers. This should be deleted for a storyboard app (the only code in the default template in didFinishLaunchingWithOptions: is "return YES"). It might be easier to just start a new storyboard based single view project and copy your files to it.
I understand (I think) why this isn't working, but I don't know how to get it to work.
I have a method I call in viewWillAppear like so (I've simplified the code for the sake of this question):
- (void)viewWillAppear:(BOOL)animated
{
[self displayHour:0];
}
I then have a little for loop that builds some buttons in viewDidLoad:
NSUInteger b = 0;
for (UIButton *hourButton in hourButtons) {
[hourButton setTag:b];
[hourButton setTitle:[NSString stringWithFormat:#"%lu", (unsigned long)b] forState:UIControlStateNormal];
[hourButton addTarget:self action:#selector(showHour:) forControlEvents:UIControlEventTouchUpInside];
b++;
}
Then for the action I have this:
- (IBAction)showHour:(id)sender
{
// Logs 0, 1, etc. depending on which button is tapped
NSLog(#"Button tag is: %lu", (long int)[sender tag]);
// This currently throws this error:
// No visible #interface for 'UIView' declares the selector 'displayHour:'
// What I want to do is be able to call this method on
// the main view and pass along the button tag of the
// button that was tapped.
[mainView displayHour:(long int)[sender tag]];
}
THE QUESTION is how do I call displayHour to the main view from the showHour: action?
If you need it, the displayHour method looks like this (simplified, basically updates some labels and image views on the main view):
- (void)displayHour:(NSUInteger)i
{
// The temperature
hourTemp = [[hourly objectAtIndex:i] valueForKeyPath:#"temperature"];
// The icon
hourIcon = [[hourly objectAtIndex:i] valueForKeyPath:#"icon"];
// The precipitation
hourPrecip = [[hourly objectAtIndex:i] valueForKeyPath:#"precipProbability"];
// SET DISPLAY
[hourTempField setText:hourTemp];
[hourIconFrame setImage:hourIcon];
[hourPrecipField setText:hourPrecip];
}
Thanks!
Instead of
[mainView displayHour:(long int)[sender tag]];
do:
[self displayHour:(long int)[sender tag]];
I have eight (8) UIButtons setup in my game. When one is selected it shows that it is selected and if you click it again it will show as unselected. However, I want to make it so that when you select a button and any of the other seven (7) are selected, they become unselected.
I know how to do this through the use of [buttonName setSelected:NO] but the problem is I can't pass buttonOne to buttonTwo if buttonTwo has already been passed to buttonOne because I have already imported buttonTwo's header file in buttonOne. It throws a parse error if I have both headers importing each other. I've been stuck on this for a while now and was hoping that someone might have a solution to my problem.
Thanks for any help.
Get the parent view of the current button and iterate through all the buttons inside, unselecting all of them. Then, select the current one.
// Unselect all the buttons in the parent view
for (UIView *button in currentButton.superview.subviews) {
if ([button isKindOfClass:[UIButton class]]) {
[(UIButton *)button setSelected:NO];
}
}
// Set the current button as the only selected one
[currentButton setSelected:YES];
Note: As suggested on the comments, you could keep an array of buttons and go over it the same way the above code does with the subviews of the parent view. This will improve the performance of your code in case the view containing the buttons has many other subviews inside.
I know its too late to answer this question but I did it in only small lines of code . Here is what i did :
NSArray *arrView = self.view.subviews;
for (UIButton *button in arrView) {
if ([button isKindOfClass:[UIButton class]]) {
[((UIButton *) button) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
}
[button1 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
Simple way to do.
-(void)buttonSelected:(id)sender{
UIButton *currentButton = (UIButton *)sender;
for(UIView *view in self.view.subviews){
if([view isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton *)view;
[btn setSelected:NO];
}
}
[currentButton setSelected:YES];
}
I actually created an answer by reading all of your guys input, which I thank you greatly for. The tag property of the UIButton class was unknown to me before this post.
I created own subclass of UIButton, let's call it CustomUIButton.m. I created a NSMutableArray property for use when storing the buttons, which I'll call customButtonArray.
When I created the button, I set the tag property, and added the button to a local array on the parent view controller. After all buttons I wanted were created, I set the customButtonArray, like so:
// Initialize buttonHolderArray
NSMutableArray *buttonHolderArray = [[NSMutableArray alloc] init];
// Create a button
CustomUIButton *newButton = [[CustomUIButton alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
newButton.tag = 1;
[newButton setImage:[UIImage imageNamed:#"newButtonUnselected" forControlState:UIControlStateNormal]];
[buttonHolderArray addObject:newButton];
// Create additional buttons and add to buttonHolderArray...
// using different numbers for their tags (i.e. 2, 3, 4, etc)
// Set customButtonArray property by iterating through buttonHolderArray
NSInteger buttonCount = [buttonHolderArray count];
for (int i = 0; i < buttonCount; i++)
{
[[buttonHolderArray objectAtIndex:i] setCustomButtonArray:buttonHolderArray];
}
To deselect any other button selected when a different buttons handleTap: is called, I iterated through the customButtonArray in the subclass main file and set the selected property to NO. I also set the correct image from another array property that I manually populated with the images, which I did so the array didn't have to be populated every time a button was pressed. At the end, unselected all other buttons, like so:
// Populate two arrays: one with selected button images and the other with
// unselected button images that correspond to the buttons index in the
// customButtonArray
NSMutableArray *tempSelectedArray = [[NSMutableArray alloc] init];
[tempSelectedArray addObject:[UIImage imageNamed:#"newButtonSelected"]];
// Add the other selected button images...
// Set the property array with this array
[self setSelectedImagesArray:tempSelectedArray];
NSMutableArray *tempUnselectedArray = [[NSMutableArray alloc] init];
[tempUnselectedArray addObject:[UIImage imageNamed:#"newButtonUnselected"]];
// Add the other unselected button images...
// Set the property array with this array
[self setUnselectedImagesArray:tempUnselectedArray];
- (void)handleTap:(UIGestureRecognizer *)selector
{
// Get the count of buttons stored in the customButtonArray, use an if-elseif
// statement to check if the button is already selected or not, and iterate through
// the customButtonArray to find the button and set its properties
NSInteger buttonCount = [[self customButtonArray] count];
if (self.selected == YES)
{
for (int i = 0; i < buttonCount; i++)
{
if (self.tag == i)
{
[self setSelected:NO];
[self setImage:[[self unselectedImagesArray] objectAtIndex:i] forControlState:UIControlStateNormal];
}
}
}
else if (self.selected == NO)
{
for (int i = 0; i < buttonCount; i++)
{
if (self.tag == i)
{
[self setSelected:NO];
[self setImage:[[self selectedImagesArray] objectAtIndex:i] forControlState:UIControlStateNormal];
}
}
}
for (int i = 0; i < buttonCount; i++)
{
if (self.tag != i)
{
[self setSelected:NO];
[self setImage:[[self unselectedImagesArray] objectAtIndex:i] forControlState:UIControlStateNormal];
}
}
}
Thanks for all of the useful information though, figured I should share the final answer I came up with in detail to help anyone else that comes across this problem.
I figured out a pretty easy way to solve this. My example is for 2 buttons but you can easily add more if statements for additional buttons. Connect all buttons to the .h file as properties and name them (I did button1 & button2). Place the following code in your .m file and Connect it (via the storyboard) to all of your buttons. Make sure when you are setting up your button to set an image for BOTH the normal UIControlStateNormal & UIControlStateSelected or this wont work.
- (IBAction)selectedButton1:(id)sender {
if ([sender isSelected]) {
[sender setSelected:NO];
if (sender == self.button1) {
[self.button2 setSelected:YES];
}
if (sender == self.button2) {
[self.button1 setSelected:YES];
}
}
else
{
[sender setSelected:YES];
if (sender == self.button1) {
[self.button2 setSelected:NO];
}
if (sender == self.button2) {
[self.button1 setSelected:NO];
}
}
To answer "It throws a parse error if I have both headers importing each other"...
You should refrain from using #import in .h files as much as possible and instead declare whatever you're wanting to use as a forward class declaration:
#class MyCustomClass
#interface SomethingThatUsesMyCustomClass : UIViewController
#property (nonatomic, strong) MyCustomClass *mcc;
#end
Then #import the header in your .m file:
#import "MyCustomClass.h"
#implementation SomethingThatUsesMyCustomClass
-(MyCustomClass *)mcc
{
// whatever
}
#end
This approach will prevent errors caused by #import cycles.
Though I must say I agree with SergiusGee's comment on the question that this setup feels a bit strange.
The easiest approach here would be to get the parent UIView the buttons are on and iterate through it. Here's a quick example from my code:
for (UIView *tmpButton in bottomBar.subviews)
{
if ([tmpButton isKindOfClass:[UIButton class]])
{
if (tmpButton.tag == 100800)
{
tmpButton.selected = YES;
[tmpButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[tmpButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];
}else{
tmpButton.selected = NO;
[tmpButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[tmpButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
}
}
}
Did you try using ReactiveCocoa framework and add some blocks for your code , this is not the most simple approach yet i would say it is the most effective when you have multiple dependencies and very good for scaling
I have created a small project for a solution to your problem using my suggested approach (I tried to adapt it to the good old MVC pattern instead of my preferred MVVM)
you can find it here
https://github.com/MWaly/MWButtonExamples
make sure to install cocoa pods file as we need "ReactiveCocoa" and "BlocksKit" for this sample
we will use two main classes
ViewController => The viewController object displaying the buttons
MWCustomButton => Custom UIButton which handles events
when creating the buttons a weak reference to the viewController is also created using the property
#property (weak) ViewController *ownerViewController ;
events will be handled using the help of blocksKit bk_addEventHandler method and pass it to the block of the ViewController (selectedButtonCallBackBlock)
[button bk_addEventHandler:^(id sender)
{
self.selectedButtonCallBackBlock(button);
} forControlEvents:UIControlEventTouchUpInside];
now in the ViewController for each button touched the callBackButtonBlock will be trigerred , where it will change its currently selected button if applicable
__weak __typeof__(self) weakSelf = self;
self.selectedButtonCallBackBlock=^(MWCustomButton* button){
__typeof__(self) strongSelf = weakSelf;
strongSelf.currentSelectedButton=button;
};
in the MWCustomButton class , it would listen for any changes in the property of "currentSelectedButton" of its ownerViewController and will change its selection property according to it using our good Reactive Cocoa
///Observing changes to the selected button
[[RACObserve(self, ownerViewController.currentSelectedButton) distinctUntilChanged] subscribeNext:^(MWCustomButton *x) {
self.selected=(self==x);
}];
i think this would solve your problem , again your question might be solved in a simpler way , however i believe using this approach would be more scalable and cleaner.
Loop through all views in parent view. Check if it is a UIButton(or your custom button class) and not the sender. Set all views isSelected to false. Once loop is finished, set sender button isSelected to true.
Swift 3 way:
func buttonPressed(sender: UIButton) {
for view in view.subviews {
if view is UIButton && view != sender {
(view as! UIButton).isSelected = false
}
}
sender.isSelected = true
}
Swift 4
//Deselect all tip buttons via IBOutlets
button1.isSelected = false
button2.isSelected = false
button3.isSelected = false
//Make the button that triggered the IBAction selected.
sender.isSelected = true
//Get the current title of the button that was pressed.
let buttonTitle = sender.currentTitle!
i have a Navigation Bar, wich contains a Navigation Item, which contains 2 Bar Buttons, these are created in the Storyboard, and i wanted to change 1 of the buttons at runtime, now this works:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UINavigationItem *thisNavBar = [self myNavigationItem];
thisNavBar.rightBarButtonItem = nil; // this works, it gets removed
UIBarButtonItem *insertBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(insertSkemaItem:)];
thisNavBar.rightBarButtonItem = insertBtn; // this also works, it sets the btn
}
Now, in my other method, which is called by another controller, it does not work
- (void)callChildChange {
...
// remove old btn
UINavigationItem *thisNavBar = [self skemaNavigationItem];
thisNavBar.rightBarButtonItem = nil; // does not work?
}
There is nothing wrong with the method, it runs just fine, but the nav btn item does not get removed ?
skemaNavigationItem is a Navigation item, declared in the .h file which links the navigation item i made via the storyboard.
Your UI items need to be added to your code (by ctrl-dragging) in the header file (.h) so they can be publicly accessed from other classes/view controllers.
Presuming you've done this, hiding a UI item is best done by using
relevantClass.yourViewObject.hidden = YES;
or if you really need to delete it for good,
[relevantClass.yourViewObject.view removeFromSuperView];
Edits
Options for changing target method:
Declare #property (nonatomic, assign) BOOL myButtonWasPressed; and:
- (IBAction) myButtonPressed
{
if (!self.myButtonWasPressed)
{
// This code will run the first time the button is pressed
self.myButton.text = #"New Button Text";
self.myButtonWasPressed = YES;
}
else
{
// This code will run after the first time your button is pressed
// You can even set your BOOL property back, and make it toggleable
}
}
or
- (IBAction) myButtonWasPressedFirstTime
{
// do what you need to when button is pressed then...
self.myButton.text = #"New Button Text";
[self.myButton removeTarget:self action:#selector(myButtonPressedFirstTime) forControlEvents:UIControlEventTouchUpInside];
[self.myButton addTarget:self action:#selector(myButtonPressedAgain) forControlEvents: UIControlEventTouchUpInside];
}
- (IBAction) myButtonWasPressedAgain
{
// this code will run the subsequent times your button is pressed
}