how do i use if buttons to trigger if statements in xcode? - ios

So i am creating a tic tac toe game (user vs computer) and i want to have -(IBAction) statements with if statements thats would say if(buttonIsPressed), do ____. I cant just say
-(IBAction)button:(id)selector;{
//stuff i want
}
because the buttons are pressed in different order and the computer would have different responses (i want there to be an order). For example, this is what i tried,
-(IBAction)move2;{
if (buttona2){
c2.image = [UIImage imageNamed:#"imgres-3.jpg"];
}
it didnt work because the the result of this if statement ( c2.image = [UIImage imageNamed:#"imgres-3.jpg"];) would start automatically and not run depending on the pressing of the button (it runs right away). Pretty much i want the if statement to run on press of a button (or not work if the button is not pressed.
Can anyone help?

If I understand your question right, you want to check if a button is toggled on or off before running the if statement right? In that case, I would declare a BOOL in your header file
#property BOOL toggle;
Then in your implementation file when the user presses the button the target of the button should have the code:
if(self.toggle == TRUE){
self.toggle = FALSE;
//and any visual UI change you want to show that the button is now off
}else{
self.toggle = TRUE;
//and any visual change you want to show that the button is now on
}
Then in your -(IBAction) your code becomes:
-(IBAction)move2;{
if (self.toggle){
c2.image = [UIImage imageNamed:#"imgres-3.jpg"];
}
}
And that should work.

Related

How to tell if a button is pressed at a certain time

I have a button with an image, and after a little while the button image will change, then change back after a few seconds. I want to be able to tell if the button is clicked while the image is different. thanks!
You have several options, but I'll detail two of them. The first is more self-contained and foolproof, but the second is arguably easier to read and understand.
Check the background image
The easiest way to do this would probably be to just test against the image itself. The image changes from time to time, but you don't really care when the button is pressed, you just care which background is visible when it is.
In other words, all you really need to know is whether the button's background is the MainBackground or the AlternateBackground, so when the button is pressed, you can simply check which one it is.
Try something like this, for when the button is pressed:
-(void)buttonPressed:(UIButton*)sender {
UIImage *mainBackground = [UIImage imageNamed:#"YOUR_IMAGE_NAME"];
NSData *imgdata1 = UIImagePNGRepresentation(sender.image);
NSData *imgdata2 = UIImagePNGRepresentation(mainBackground);
if ([imgdata1 isEqualToData:imgdata2]) {
// The button's background is the MainBackground, do one thing
} else {
// The button's background is the AlternateBackground, do another thing
}
}
Keep track of which image is currently displayed
Alternatively, you could have a BOOL value flip whenever the image's background is changed. Something like...
#property BOOL isMainBackground;
...in your H file, and then whenever you set the button's background image, you also set self.isMainBackground = YES; or self.isMainBackground = NO;
Then, your method for the button press would look something like this:
-(void)buttonPressed:(UIButton*)sender {
if (self.isMainBackground) {
// The button's background is the MainBackground, do one thing
} else {
// The button's background is the AlternateBackground, do another thing
}
}

Stuck with UIActionSheetPicker , iOS

This is going to be a very targeted question , as its for people that have actually used the UIActionSheetPicker before.
I used it in my iphone applications and everything worked great , but now that i tried to implement it on my ipad i experienced some problems.
The main problem is that on ipad the picker appears as a "bubble" or "info window" if you prefer , which points at the spot where it was called , like a button a text field etc.
Below is an example of it :
You can see that the "info window" is pointing at the animals button.
In my application i have 4 different buttons. 2 are in the top side of the screen and 2 at the bottom.
Those who are at the bottom , call the picker very well and the picker appears on top of the buttons pointing down on them.
However , the ones on the top of the screen (almost like the one in the image) when they call the picker the picker appears much lower on the screen and doesnt point at them as it should ...
I mean i expected to appear just under the buttons pointing at them (like in the image), but they are almost in the center of the screen pointing nowhere..
Any ideas? Has someone experienced this before?
EDIT
In the beginning , i was calling the ActionSheetPicker inside the buttons action like this:
- (IBAction)selectTopic:(UIControl *)sender {
[ActionSheetStringPicker showPickerWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
//when user picks a new topic we clean the titleField to make sure selected title of previous topic doesnt mix up with new topic
titleField.text = #"";
}
Now i am trying to call it like this:
- (IBAction)selectTopic:(UIControl *)sender {
ActionSheetStringPicker *thePicker = [[ActionSheetStringPicker alloc] initWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
thePicker.presentFromRect = topicField.frame;
[thePicker showActionSheetPicker];
//when user picks a new topic we clean the titleField to make sure selected title of previous topic doesnt mix up with new topic
titleField.text = #"";
}
Where topicField is my TextField.
Sadly the result is the same. Even now that i am specifying where i want the arrow to point , the picker is called 300 pixels down.
The strange thing is though that even with another other button that is a bit lower than the previous the picker is again exactly 300 pixels down.
EDIT2
After noticing that the picker shows 300 pixels down , i decided to manually make it show 300pixels up , to point exactly on my button.
I used the following code :
- (IBAction)selectTopic:(UIControl *)sender {
//[ActionSheetStringPicker showPickerWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
ActionSheetStringPicker *thePicker = [[ActionSheetStringPicker alloc] initWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
CGRect pickerFrame = topicField.frame;
pickerFrame.size.height -= 300;
thePicker.presentFromRect = pickerFrame;
[thePicker showActionSheetPicker];
//when user picks a new topic we clean the titleField to make sure selected title of previous topic doesnt mix up with new topic
titleField.text = #"";
}
Amazingly the button once again appears in the same position 300pixels down. I start to believe that this one may not be the property to alter the position of the picker.
Any ideas ?
Setting the presentFromRect in your calling code won't make a difference since it will be reset based on the sender within the ActionSheetPicker code, instead you are going to need to modify the source code of the library.
The following (unmerged) commit on github should resolve the issue On iPad, set the popover to point properly at its container.
Basically within the AbstractActionSheetPicker.m file modify the - (void)presentPickerForView:(UIView *)aView method like the following
- (void)presentPickerForView:(UIView *)aView {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
self.presentFromRect = CGRectMake(0, 0, self.containerView.frame.size.width, self.containerView.frame.size.height);
[self configureAndPresentPopoverForView:aView];
}
else {
self.presentFromRect = aView.frame;
[self configureAndPresentActionSheetForView:aView];
}
}
After a brief look at the code, I would say that you want to make sure that the presentFromRect on the ActionPicker object is in the coordinates of the container that you are passing in on the init. For instance if I had one big view that contained a button:
This is untested:
UIView* someBigView = ... // get the big view
UIButton* someButton = ... // get the button that the big view contains
ActionSheetDatePicker* thePicker = [[ActionSheetDatePicker alloc] initWithTitle:#"Some Title"
datePickerMode:UIDatePickerModeDate
selectedDate:[NSDate date]
target:self
action:#selector(someMethod:)
origin:someBigView];
//the arrow should be pointing at the button
thePicker.presentFromRect = someButton.frame;
[thePicker showActionSheetPicker];
In my opinion, this library has a pretty big flaw in the fact that it takes an origin parameter that can be a button item or a container. It requires that you look at the source to understand it, instead of being (somewhat) obvious from the interface.

Reloading a non-table view (iOS)

I'm working on a painting app, and I want to user to be able to switch through paintings that are saved as PNGs to the documents directory. I've made an IBAction that does this:
-(IBAction)switchPage:(id)sender{
if ([sender tag] ==1)
{
currentImage=currentImage-1;
}
else
{
currentImage++;
}
[[NSUserDefaults standardUserDefaults] setInteger:currentImage forKey:#"currentDoc"];
[self.view setNeedsDisplay];
}
Just to let you know, I have 2 buttons, a back and forward, and they're connected to the same IBAction that's pasted above. The back button has a tag of 1, and the forward button doesn't have a tag. currentImage is an int that is used to set an image's name, so if currentImage =1, then it would set the image to image1. But that's not what I'm having trouble with, I'm having trouble "reloading" the view. I'm using setNeedsDisplay, but it's not working, and I know that reloadData is only for UITables, so what else could I use?
I've been searching for an answer, but none of the existing questions about this don't have a clear answer, or are under different circumstances.
Thanks for your time and/or dealing with a stupid question, as I'm new to Xcode.
-Karl
I see no view code in your post.
Assuming you have a UIImageView that is displaying the image you would just do:
myImageView.image = whateverUIImage;

Change background image of a button without extra buttons

I've set a button with an image as it's background, and I'm trying to get the image to change back and forth from 2 different images when pressed.
For example, a happy face when pressed would switch to a sad face, and when pressed again would switch back to a happy face and so on.
Any help you can offer would be amazing before I pull anymore hair out.
set the images for two different states: normal and selected,
have the button target an action that toggles the selected state on the button/sender
UIButton* myButton;
- (IBAction)buttonPressed {
if(alreadySelected) {
myButton.imageView.image = myNormalImage;
} else {
myButton.imageView.image = mySelectedImage;
}
}
Not sure, but I think this should do it.
What BoopMeister said, except as bshirley pointed out, you need this API call:
[myButton setImage:happyImage forState:UIControlStateNormal];

Memory management problem (release UIVIewCotroller)

I develop the game for iPad (composing image from puzzles). In my menu i choose level difficult (simple, medium or hard). After selecting the main playing field will be shown.
Here's place, where i create the main playing field:
- (void)simpleDiffButtonClicked:(id)sender
{
UIButton *button = sender;
if (simpleDiffButton == button) {
UIView *mySuperView = self.view.superview;
mainGame = [[MainGame alloc] initWithMode:1 andImage:nil]; //mainGame variable is declared in header file like: MainGame *mainGame;
mainGame.view.frame = CGRectMake(0, 0, 1024, 768);
[mySuperView addSubview: mainGame.view];
}
}
After this playing field is appears (there are a lot of sublayers adding to self.view.layer) and i can interact with it. When i want to quit from it, i click button "back". (here i want to release my viewcontroller)
- (void)backToMenuButtonClicked:(id)sender
{
UIButton *button = sender;
if (nextImageClick == YES) {
return;
}
if (backToMenuButton == button) {
self.view.layer.sublayers = nil; //here's an exception
[self.view removeFromSuperview];
}
}
After clicking "back" button everything is ok. And i can choose difficultly level again. A choose a level, and after it clicking "back" button again and at this place application crashes (EXC_BAD_ACCESS).
As i understand "self.view.layer.sublayers = nil" causes the exception.
Without it everything is ok. But memory is leaking. And after several minutes of playing app was crashes (memory warning 2).
I cannot solve the problem for about a week. I don't understand what to do to release my viewcontroller (or i need to release all sublayers in controller?).
Please, someone help me.
Thanks in advance.
Try to turn on NSZombieEnabled and check out Debugger and Console when it crush, it can give some more info about the problem.
P.S. NSZombieEnabled : http://www.cocoadev.com/index.pl?NSZombieEnabled (you may want to try useing .gdbinit).
P.P.S:
Btw, there might be some other problem in the line where "mainGame = [[MainGame alloc] initW...". -- where [mainGame release] is called? (it should be called as many as simpleDiffButtonClicked which allocs new instance of MainGame to mainGame variable (every time))

Resources