iOS App crash on button click - ios

I am creating buttons inside the for loop below shown is the code for that
for(int i=1;i<[_imageDetailsEntities count];i++)
{
UIButton *bttn=[UIButton buttonWithType:UIButtonTypeCustom];
bttn.frame=CGRectMake(x,y,75,75);
[_scrollView addSubview:bttn];
ImageDetails *imageDetails=[_imageDetailsEntities objectAtIndex:i];
UIImage *image= [self imageFromPath:imageDetails.imagePath];
[bttn setImage:image forState:UIControlStateNormal];
bttn.tag=i-1;
[bttn addTarget:self action:#selector(imageTapped:) forControlEvents:UIControlEventTouchUpInside];
x=bttn.frame.origin.x+bttn.frame.size.width+distanceBetweenButtons;
if(i%3==0)
{
x=29;
y=y+bttn.frame.size.height+20;
}
}
[_scrollView setContentSize:CGSizeMake(320,y+95)];
-(void)imageTapped:(id)sender
{
UIButton *bttn=(UIButton*)sender;
[_delegate didFinishChoosingImageAtIndex:bttn.tag];
}
App is crashing with EXC_Bad access message when i tap a button.I am using ARC. I am not sure, what i am missing here.Please help me

Try replacing following line under imageTapped:
[_delegate didFinishChoosingImageAtIndex:bttn.tag];
with
if([_delegate respondsToSelector:#selector(didFinishChoosingImageAtIndex:)]){
[_delegate didFinishChoosingImageAtIndex:bttn.tag];
}

Try turning on NSZombie and see if something is being released too soon.EXC_BAD_ACCESS means that something was already deallocated when you sent it the message.

Don't know what your code does exactly, but it looks like your for-loop has a one-off error.
Either use
for(int i=0;i<[_imageDetailsEntities count];i++)
or
for(int i=1;i<=[_imageDetailsEntities count];i++)
if you want to iterate over all thingies.

you should maintain an array of the buttons in your controller, so ARC doesnt dealloc them.
In your interface:
#property (nonatomic, strong) NSMutableArray *buttons;
Your code:
NSMutableArray *buttons = [NSMutableArray array];
for(int i=1;i<[_imageDetailsEntities count];i++)
{
...your code
[buttons addObject:bttn];
}
self.buttons = buttons;
You could use that array again to remove buttons from the view if need be.

Related

UIWebView only loads link after the second try

I've searched this issue for a solid amount of time, and I couldn't find an answer that solved my problem. If there are any similar questions that I missed and that have a working solution, please post a link to them.
Anyways...
I have a menu filled with buttons that, when clicked, opens up a UIWebView which opens a specific webpage. Everything works fine, but only after the second try. To be a little more clear, the first time I tap a button, the webpage gets stuck loading, but after you close it out and tap it again, the pages load up just fine.
Since I'm using multiple buttons, I decided to put them all in an IBOutlet Collection:
#property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *btnArray;
I then set up an array that would hold all the buttons from the collection, set up a view controller for our webview class (we have a separate class for webviews, which has not caused me any problems in the past) and the webview's navigation controller, and finally I used a for loop to add all the buttons the array.
NSMutableArray *theButtons = [[NSMutableArray alloc] init];
webVC = [[WebviewViewController alloc] init];
webNav = [[UINavigationController alloc] initWithRootViewController:webVC];
for(int i = 0; i < [btnArray count]; i++)
{
UIButton *btn = btnArray[i];
btn.tag = i;
[theButtons addObject:btn];
[theButtons[i] addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
I also have set up an array with the end links of all the pages I need to go to, which will be appended to a url:
pages = #[#"exOne.php", #"exTwo.php", #"exThree.php", #"exFour.php", #"exFive.php", #"exSix.php"];
Note: all the above code in -viewDidLoad
Here is the method that handles what happens when a button is clicked:
-(void)buttonPressed : (id) sender
{
UIButton *clicked = (UIButton *) sender;
NSMutableString *url = [NSMutableString stringWithString:#"http://www.example.org/examples/"];
for(int i = 0; i < [btnArray count]; i++)
{
if(i == clicked.tag)
{
[url appendString:pages[i]];
[webVC loadURL:url];
webNav.navigationBar.translucent = NO;
webNav.navigationBar.topItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:self action:#selector(backPressed)];
[self.navigationController pushViewController:webVC animated:YES];
}
}
}
If it wasn't clear from the method call
[webVC loadURL:url];
just sends the link to our webviewViewController class and loads the link.
Any ideas on why the webpages only load after the second attempt?
Your WebviewViewController has probably not been loaded when you call loadURL the first time. If the view controller is not loaded it's subviews and hence it's embedded UIWebView are not available. When you push the controller it gets loaded and the second time loadURL will work.

Using programmatically created UIButtons with the same method to load different UIViewControllers

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.

Cocos2D: Obtaining the text from a CCMenuItemFont

I guess I'm missing something obvious, but I simply can't figure out how to obtain the label of a CCMenuItemFont.
Background
I'm building a simple hangman game for the iPad. For entering the next guess, I've added 26 buttons to the UI (one for each letter of the alphabet) and wired them all to the same event handler.
Now, inside the event handler, I'd like to obtain the label of the button to update the current guess, but CCMenuItemFont apparently doesn't respond to text or label.
Problem
So - what method can I use to obtain the label of a CCMenuItem?
Code
Code for creating the buttons:
-(void)addButtons {
NSArray* charArray = [NSArray arrayWithObjects:
#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",
#"L",#"M",#"N",#"O",#"P",#"Q",#"R",
#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
[CCMenuItemFont setFontName:#"Marker Felt"];
[CCMenuItemFont setFontSize:45];
NSMutableArray* buttonArray = [NSMutableArray array];
for (unsigned int i=0; i < [charArray count]; ++i) {
CCMenuItemLabel* buttonMenuItem = [CCMenuItemFont
itemWithString:(NSString*)[charArray objectAtIndex:i]
target:self selector:#selector(buttonTapped:)];
buttonMenuItem.color = ccBLACK;
buttonMenuItem.position = ccp(60 + (i/13)*40, 600 - (i%13)*40);
[buttonArray addObject:buttonMenuItem];
}
CCMenu *buttonMenu = [CCMenu menuWithArray:buttonArray];
buttonMenu.position = CGPointZero;
[self addChild:buttonMenu];
}
And the event handler:
- (void)buttonTapped:(id)sender {
// Get a reference to the button that was tapped
CCMenuItemFont *button = (CCMenuItemFont *)sender;
[_guess addObject:[button text]]; // this throws an exception because text is the wrong method
[self paintCurrentGuess];
}
You're adding to your menu a CCMenuItemLabel, not a CCMenuItemFont (which actually extends the first one). In both cases, you need to access to the inner label containing the text.-
CCMenuItemLabel *button = (CCMenuItemLabel *)sender;
NSString *label = button.label.string;

How to send method to view from action called by UIButton

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]];

Deselect all UIButtons when one is selected

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!

Resources