How to add amount into UITextField on click of UIButton - ios

I have aUITextField and below that 3 button. User can enter the amount inUITextField. And When user clicked the button belowUITextField it will add the amount inUITextField with amount written in button.
First button will add 100, Second will add 500 ad 3rd will add 1000. What is the best method to achieve it.
I try to implement following but got button.tag=0
/*Amount increment*/
- (IBAction)Btn_Incr100:(id)sender {
[self addTextFieldValue:nil];
}
- (IBAction)Btn_Incr500:(id)sender {
[self addTextFieldValue:nil];
}
- (IBAction)Btn_Incr1000:(id)sender {
[self addTextFieldValue:nil];
}
-(void)tagNumber{
Btn_Incr100.tag=1;
Btn_Incr500.tag=2;
Btn_Incr1000.tag=3;
}
-(void) addTextFieldValue:(UIButton*) button
{
int amount=[Txt_Amount.text intValue];
int AddAmount;
NSLog(#"button.tag%d",button.tag);
if (button.tag==1) {
AddAmount=100;
}
else if (button.tag==2) {
AddAmount=500;
}
else if(button.tag==3) {
AddAmount=1000;
}else{
AddAmount=0;
}
amount=amount+AddAmount;
Txt_Amount.text=[NSString stringWithFormat:#"%d",amount];
NSLog(#"%d",amount);
NSLog(#"%#",Txt_Amount.text);
}

Try using it by implementing tag
- (void)viewDidLoad {
[super viewDidLoad];
[self tagNumber];
}
-(void)tagNumber{
Btn_Incr100.tag=1;
Btn_Incr500.tag=2;
Btn_Incr1000.tag=3;
}
-(void) addTextFieldValue:(UIButton*) button
{
int amount=[Txt_Amount.text intValue];
int AddAmount;
int buttonTagIndex = button.tag;
switch (buttonTagIndex) {
case 1:
AddAmount=100;
break;
case 2:
AddAmount=500;
break;
case 3:
AddAmount=1000;
break;
default:
AddAmount=0;
break;
}
amount=amount+AddAmount;
Txt_Amount.text=[NSString stringWithFormat:#"%d",amount];
}
- (IBAction)btnAmountClick:(id)sender{
UIButton *button = sender;
[self addTextFieldValue:button];
}

With the help of this you can achieve:
-(void)displayvalue:(id)sender {
UIButton *resultButton = (UIButton *)sender;
NSLog(#" The button's title is %#." resultButton.currentTitle);
}
and now you can set this text inside your textfield.

Add this method as every button action.
-(void) addTextFieldValue:(UIButton*) button
{
NSString *string;
if ([button.text hasPrefix:#"+"] && [button.text length] > 1)
{
string = [string substringFromIndex:1];
}
int textFieldValue =[textField.text integerValue] + string.integerValue;
textField setText:[NSString stringWithFormat:#"%i",textFieldValue];
}

NSString *string;
if ([button.text hasPrefix:#"+"] && [button.text length] > 1)
{
string = [string substringFromIndex:1];
}
int textFieldValue =[textField.text integerValue] + string.integerValue;
textField setText:[NSString stringWithFormat:#"%i",textFieldValue];
or
connect separate actions
-(IBAction) onClick1: (id) sender]
{
NSLog(#"User clicked %#", sender);
textField.text = [textField.text integerValue] + 100
}

You can do this way -
The three buttons below your textfield, link them all to a common method say,
-(IBAction)addBtnClicked:(UIButton *)btn
Given tags to three buttons like for button 100,
btn1.tag=100..
then for button 500,
btn2.tag = 500..
then for button 1000, btn2.tag = 1000.
then in
-(IBAction)addBtnClicked:(UIButton *)btn
{
int value = -1;
if(btn.tag == 100)
{
value =[txtFldText.text intValue] + 100;
}
else if(btn.tag == 500)
{
value =[txtFldText.text intValue] + 500;
}
else if(btn.tag == 1000)
{
value =[txtFldText.text intValue] + 1000;
}
txtFldText.text = [NSString stringWithFormat:#"%d",value];
}

Simply you can do like this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_txtAmount.text=#"0";
_btn100.tag=100;
_btn500.tag=500;
_btn1000.tag=1000;
}
- (IBAction)btnAmountClick:(id)sender
{
UIButton *btn=sender;
if (btn.tag==100)
{
[self addAmount:#"100"];
}
if (btn.tag==500)
{
[self addAmount:#"500"];
}
if (btn.tag==1000)
{
[self addAmount:#"1000"];
}
}
-(void)addAmount:(NSString*)strAmount
{
int amount=[_txtAmount.text intValue]+[strAmount intValue];
_txtAmount.text=[NSString stringWithFormat:#"%d",amount];
}

First set tag to every button like 0,1,2.
then connect IBOutlet of all button to single IBAction and
implement the IBAction as below.
- (IBAction)btnClicked:(id)sender
{
switch ([sender tag]) {
case 0:
{
NSString *s=self.txtField.text;
int add=[s intValue]+ 100;
self.txtField.text=[NSString stringWithFormat:#"%d",add];
break;
}
case 1:
{
NSString *s=self.txtField.text;
int add=[s intValue]+ 200;
self.txtField.text=[NSString stringWithFormat:#"%d",add];
}
break;
case 2:
{
NSString *s=self.txtField.text;
int add=[s intValue]+ 500;
self.txtField.text=[NSString stringWithFormat:#"%d",add];
}
break;
default:
break;
}
}

There's a better solution for this.
You can use tags smth differently, as they are.
Just tie your three buttons as actions to this method and set the tags to 100/500/1000
- (void)buttonAction:(id)sender {
textField.text = [NSString stringWithFormat:#"%li", (long)(textfield.text.intValue + sender.tag)];
}

Related

How to tell if all buttons in an array are not selected

I have an array of buttons:
pokemon_cards = [[NSMutableArray alloc] init];
[pokemon_cards addObject:self.cardButton1];
[pokemon_cards addObject:self.cardButton2];
[pokemon_cards addObject:self.cardButton3];
later in some method I want to do a BOOL check to see if ALL of them are NOT selected simultaneously. In other words, if ALL of them are not selected notify user, otherwise proceed, even if just one of them is selected.
Here is what i've done but its not working and I can't figure out how to do this without adding the buttons in the loop to a temporary array:
-(BOOL)userCanProceedToTurn {
for (UIButton *button in pokemon_cards) {
if (![button isSelected]) {
// This only works for OR condition I want it to work for &&
return NO;
} else {
return YES;
}
}
}
So this is what I want it to do pretty much but the function above doesn't work for &&:
if (![self.cardButton1 isSelected] && ![self.cardButton2 isSelected] && ![self.cardButton3 isSelected]) {
//notify users they must selected at least one card
} else {
}
But i don't know which cards will be added to the array, that depends on the user, so I don't know how to check for that in the for loop
EDIT
I have implemented the code as suggested below. and as mentioned before this does not the && check that I was concerned with.
For example i need to make sure ALL cards are not currently in the 'not selected' state. but if one of those 3 cards are then they can proceed, even if the other two aren't. but with the check below, it will not proceed because the else statement is in the loop as well so everytime the loop is ran the buttons that aren't selected cause it to not proceed because the loop is ran 3 times.
here is my complete bool method, everything else works fine except the button one:
-(BOOL)userCanProceedToTurn {
if (self.energyAmount == 0) {
UIAlertView *view .. tell users they need energy before proceeding
return NO;
}
if (self.usernameLabel.text.length == 0) {
//Tell user they are not signed in
return NO;
}
NSLog(#"button is %lu", (unsigned long)pokemon_cards.count);
for (UIButton *button in pokemon_cards) {
if ([button isSelected]) {
NSLog(#"button.tag == %lu",button.tag);
return YES;
} else {
UIAlertView *view .. tell users they need to select at least one card
//this gets called because the loop is ran as many times there are buttons so inevitably i'll get an error. Which is why this works for the first button only, because it stops looping after it found that one since it was the first once selected
return NO;
}
}
return YES;
}
Do you actually need to know the state of each button?
Why not take the opposite approach:
- (BOOL)userCanProceedToTurn {
for (UIButton *button in pokemon_cards) {
if ([button isSelected]) {
return YES;
}
}
return NO;
}
EDIT
As a rule of thumb, methods that return a BOOL value should start with a flag set to YES or NO and only invert that flag, never setting it back to its original value. So basically, start with with BOOL result = YES and only flip it to NO, never ever flip it back to YES. This will have the pseudo-security of preventing something bad to happen.
Here's your method rewritten with this concept:
- (BOOL)userCanProceedToTurn {
BOOL isEverythingOK = NO;
NSString *message = nil;
if (self.energyAmount != 0) {
isEverythingOK = YES;
} else {
message = #"You need energy before proceeding.";
}
if (self.usernameLabel.text.length != 0) {
isEverythingOK = YES;
} else {
message = #"You are not signed in.";
}
for (UIButton *button in pokemon_cards) {
if ([button isSelected]) {
isEverythingOK = YES;
} else {
message = #"You need to select at least one card"
}
}
if (!isEverythingOK) {
UIAlertView *alert = [[UIAlertView alloc] initWith use the message here]
}
return isEverythingOK
}
We can sum up the questions, answers and comments. You can use these methods to do what you want :)
- (BOOL)userCanProceedToTurn
{
// Check Username
if (self.usernameLabel.text.length == 0)
{
[self showMessage: #"You are not signed in."];
return false;
}
// Check Energy
if (!(energyAmount > 0))
{
[self showMessage: #"You need energy before proceeding."];
return false;
}
// Check Cards
for (UIButton *button in pokemon_cards)
{
if ([button isSelected])
{
return true
}
}
[self showMessage: #"You need to select at least one card"];
return false;
}
- (void)showMessage:(NSString *)title
{
[[[UIAlertView alloc] initWithTitle: title message: nil delegate: nil cancelButtonTitle: #"OK" otherButtonTitles: nil] show];
}
If you need to know which buttons are selected then try
-(BOOL)userCanProceedToTurn
{
NSMutableArray *pokemon_cards_temp = [[NSMutableArray alloc] init];
for (UIButton *button in pokemon_cards)
{
if ([button isSelected])
{
[pokemon_cards_temp addObject:button];
}
}
// Do what you want with the selected buttons
if ([pokemon_cards_temp count] > 0)
{
return true;
}
else
{
return false;
}
}

Finding 5 in a row

Background:
Im building a game "kinda" like connect 4.
I have most of it working, the only part I'm stuck at now is determining if there are 5 of the same colors in a row (left,right,up,down & diagonal)
Question:
How can I get the code to loop and see if there are 5 pieces in a row with the same color in any direction.
Note - Each turn is played by moving one piece on the board to a new position and than 3 new pieces come into play.
That means that it would have to check for a match of 5 after the turn and also after the 3 new pieces get randomly placed onto the board.
Thank you!
My code for the game so far is..
ViewController(.m)
#import "ViewController.h"
#import "BoardCell.h"
#import <QuartzCore/QuartzCore.h>
#interface ViewController ()
#property (strong,nonatomic) NSArray *imageNames;
#property (strong,nonatomic) NSMutableArray *board;
#property NSInteger lastMove;
#define BOARDWIDTH 9
#define BOARDHEIGHT 9
#end
static int moves[]={-BOARDWIDTH,-1,1,BOARDWIDTH};
bool preSelect;
BoardCell *startCell;
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
preSelect = NO;
self.imageNames = #[#"marble_red",#"marble_blue",#"marble_purple",#"marble_orange",#"marble_green"];
self.board = [NSMutableArray new];
for (int y=0; y < BOARDWIDTH; y++) {
for (int x = 0; x < BOARDHEIGHT; x++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(5+ 35 * x, 100 + 35 * y, 30, 30);
button.tag = y*BOARDWIDTH+x;
//[button setTitle:[NSString stringWithFormat:#"%ld", button.tag] forState:UIControlStateNormal];
button.selected = NO;
[button.layer setCornerRadius:15];
[button setBackgroundColor:[UIColor colorWithWhite:.7 alpha:.5]];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: button];
[self.board addObject:[[BoardCell alloc] initWithButton:button]];
}
}
self.lastMove=arc4random_uniform(BOARDWIDTH*BOARDHEIGHT);
UIButton *button=(UIButton *)[self.view viewWithTag:self.lastMove];
[button setBackgroundImage:[UIImage imageNamed:#"greensquare"] forState:UIControlStateNormal];
[self addRandoms:3];
}
-(void) addRandoms:(NSInteger)randomCount {
for (int i = 0; i < randomCount; i++) {
int space = arc4random_uniform(BOARDWIDTH*BOARDHEIGHT);
BoardCell *cell=self.board[space];
if (!cell.occupied) {
int pic = arc4random_uniform((u_int32_t)self.imageNames.count);
NSString *string = [self.imageNames objectAtIndex:pic];
NSString *highlighted = [NSString stringWithFormat:#"%#_highlighted",string];
NSLog(#"HIGHLIGHTED = %#",highlighted);
[cell.button setBackgroundImage:[UIImage imageNamed:string] forState:UIControlStateNormal];
[cell.button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[cell.button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
cell.button.selected = NO;
cell.occupied=YES;
}
else {
i--;
}
}
}
-(void)buttonPressed:(UIButton *)button
{
NSInteger buttonId=button.tag;
BoardCell *cell=self.board[buttonId];
if (!preSelect) {
if (cell.occupied) {
//cell.button.selected = YES;
[[cell.button layer] setBorderWidth:3.5f];
[cell.button.layer setBorderColor:[[UIColor colorWithWhite:.85 alpha:.7]CGColor]];
cell.button.highlighted = YES;
preSelect = YES;
self.lastMove = buttonId;
startCell = cell;
}else{
cell.button.selected = NO;
cell.button.highlighted = NO;
[cell.button.layer setBorderColor:[[UIColor clearColor]CGColor]];
}
}else{
NSLog(#"SECOND STEP");
if (!cell.occupied) {
BoardCell *startCell=self.board[self.lastMove];
startCell.occupied=NO;
if ([self validMoveFromSquare:self.lastMove toDestination:buttonId]) {
[cell.button setBackgroundImage:[startCell.button backgroundImageForState:UIControlStateNormal]
forState:UIControlStateNormal];
[startCell.button setBackgroundImage:[UIImage imageNamed:#""] forState:UIControlStateNormal];
NSLog(#"FROM %ld, TO %ld",(long)self.lastMove,(long)buttonId);
cell.button.selected = NO;
cell.button.highlighted = NO;
startCell.button.selected = NO;
startCell.button.highlighted = NO;
self.lastMove=buttonId;
cell.occupied=YES;
preSelect = NO;
[self addRandoms:3];
}else{
startCell.occupied=YES;
preSelect = NO;
cell.button.selected = NO;
cell.button.highlighted = NO;
startCell.button.selected = NO;
startCell.button.highlighted = NO;
NSLog(#" INVALID FROM %ld, TO %ld",(long)self.lastMove,(long)buttonId);
}
}
preSelect = NO;
cell.button.selected = NO;
cell.button.highlighted = NO;
startCell.button.selected = NO;
startCell.button.highlighted = NO;
[cell.button.layer setBorderColor:[[UIColor clearColor]CGColor]];
[startCell.button.layer setBorderColor:[[UIColor clearColor]CGColor]];
}
}
-(BOOL) validMoveFromSquare:(NSInteger)startSquare toDestination:(NSInteger)destination {
for (int limit=1;limit<10;limit++ ) {
NSMutableIndexSet *visitList=[NSMutableIndexSet new];
if ([self DFSFromStart:startSquare toGoal:destination withLimit:limit andVisitList:visitList]) {
return YES;
}
}
return NO;
}
-(BOOL) DFSFromStart:(NSInteger)start toGoal:(NSInteger)goal withLimit:(NSInteger)limit andVisitList:(NSMutableIndexSet *)visitList {
if (limit >=0) {
if (((BoardCell *)self.board[start]).occupied) {
NSLog(#"Self Board = %#",self.board[start]);
return NO;
}
[visitList addIndex:start];
for (int i=0;i<4;i++) {
NSInteger nextPosition=start+moves[i];
NSLog(#"Next spot = %ld",(long)nextPosition);
if (nextPosition == goal) {
return YES;
}
if (nextPosition >=0 && nextPosition < BOARDWIDTH*BOARDHEIGHT) {
if (![visitList containsIndex:nextPosition]) {
if ([self DFSFromStart:nextPosition toGoal:goal withLimit:limit-1 andVisitList:visitList]) {
return YES;
}
}
}
}
}
return NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
BoardCell.m
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#interface BoardCell : NSObject
#property (weak,nonatomic,readonly) UIButton *button;
#property BOOL occupied;
-(id) initWithButton:(UIButton *)button;
#end
Thank you again!
You can use a recursive algorithm to work in each of the eight directions until you hit a boundary or a different color -
-(void) clearRunsOfColor:(Colors)color fromPoint:(NSInteger)startPoint {
NSInteger left=[self runFromStart:startPoint-1 ofColor:color inDirection:-1];
NSInteger right=[self runFromStart:startPoint+1 ofColor:color inDirection:1];
BOOL cleared=NO;
if (left+right+1 >4) {
[self clearBoardFromStart:startPoint-1 inDirection:-1 forLength:left];
[self clearBoardFromStart:startPoint+1 inDirection:1 forLength:right];
cleared=YES;
}
NSInteger up=[self runFromStart:startPoint-BOARDWIDTH ofColor:color inDirection:-BOARDWIDTH];
NSInteger down=[self runFromStart:startPoint+BOARDWIDTH ofColor:color inDirection:BOARDWIDTH];
if (up+down+1 > 4) {
[self clearBoardFromStart:startPoint-BOARDWIDTH inDirection:-BOARDWIDTH forLength:up];
[self clearBoardFromStart:startPoint+BOARDWIDTH inDirection:BOARDWIDTH forLength:down];
cleared=YES;
}
NSInteger NW=[self runFromStart:startPoint-BOARDWIDTH-1 ofColor:color inDirection:-BOARDWIDTH-1];
NSInteger SE=[self runFromStart:startPoint+BOARDWIDTH+1 ofColor:color inDirection:+BOARDWIDTH+1];
if (NW+SE+1 > 4) {
[self clearBoardFromStart:startPoint-BOARDWIDTH-1 inDirection:-BOARDWIDTH-1 forLength:NW];
[self clearBoardFromStart:startPoint+BOARDWIDTH+1 inDirection:BOARDWIDTH+1 forLength:SE];
cleared=YES;
}
NSInteger NE=[self runFromStart:startPoint-BOARDWIDTH+1 ofColor:color inDirection:-BOARDWIDTH+1];
NSInteger SW=[self runFromStart:startPoint+BOARDWIDTH-1 ofColor:color inDirection:+BOARDWIDTH-1];
if (NE+SW+1 > 4) {
[self clearBoardFromStart:startPoint-BOARDWIDTH+1 inDirection:-BOARDWIDTH+1 forLength:NE];
[self clearBoardFromStart:startPoint+BOARDWIDTH-1 inDirection:BOARDWIDTH-1 forLength:SW];
cleared=YES;
}
if (cleared) {
[self occupyCell:startPoint withPiece:nil];
}
}
-(void) clearBoardFromStart:(NSInteger)start inDirection:(NSInteger)direction forLength:(NSInteger) length {
NSInteger pos=start;
for (int i=0;i<length;i++) {
[self occupyCell:pos withPiece:nil];
pos+=direction;
}
}
-(NSInteger) runFromStart:(NSInteger)start ofColor:(Colors)color inDirection:(NSInteger)direction {
if ([self inBounds:start]) {
BoardCell *thisCell=self.board[start];
if (thisCell.gamepiece != nil && thisCell.gamepiece.color == color) {
if ([self validDestination:start+direction withMove:(int)direction fromSquare:start]) {
return ([self runFromStart:start+direction ofColor:color inDirection:direction]+1);
}
else {
return 1;
}
}
}
return 0;
}
-(BOOL) inBounds:(NSInteger) position {
if (position >=0 && position < BOARDHEIGHT*BOARDWIDTH) {
return YES;
}
else {
return NO;
}
}
None of the code below is tested for correctness.
You could update your BoardCell class like so:
typedef enum {
TopLeft, Top, TopRight,
Left, Right,
BottomLeft, Bottom, BottomRight,
NumberOfDirections
} BoardCellAdjacentDirection;
#interface BoardCell
- (void)addAdjacentCell:(BoardCell *)cell forDirection:(BoardCellAdjacentDirection)direction;
- (NSInteger)occupiedCellsInDirection:(BoardCellAdjacentDirection)direction;
#end
#implementation BoardCell {
NSMutableArray *adjacentCells;
}
- (instancetype)init {
if (self = [super init]) {
adjacentCells = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < (NSInteger)NumberOfDirections; i++) {
[adjacentCells addObject:[NSNull null]];
}
}
return self;
}
- (void)addAdjacentCell:(BoardCell *)cell forDirection:(BoardCellAdjacentDirection)direction {
[adjacentCells setObject:cell atIndex:(NSInteger)direction];
}
- (NSInteger)occupiedCellsInDirection:(BoardCellAdjacentDirection)direction {
if (!self.occupied) return 0;
if (adjacentCells[direction] == [NSNull null]) return 1;
return [adjacentCells[direction] occupiedCellsInDirection:direction]+1;
}
#end
Wherever you create your BoardCell objects, you'll need to add the appropriate adjacent cells. You'll also probably want to put in some sanity checks to make sure that cell adjacency is a two-way relationship (i.e. cell A is left-adjacent to B and B is right-adjacent to A).
Edit You'll probably also want to add a method to determine if you've injected a cell into the centre of a line.
typedef enum {
BackSlash,
ForwardSlash,
Vertical,
Horizontal
} BoardCellAxis;
...
- (NSInteger)occupiedCellsOnAxis:(BoardCellAxis)axis {
switch (axis) {
case BackSlash:
return MAX(0, [self occupiedCellsInDirection:TopLeft]
+ [self occupiedCellsInDirection:BottomRight]
- 1); // Don't count yourself twice.
case ForwardSlash:
return MAX(0, [self occupiedCellsInDirection:TopRight]
+ [self occupiedCellsInDirection:BottomLeft]
- 1); // Don't count yourself twice.
case Vertical:
return MAX(0, [self occupiedCellsInDirection:Top]
+ [self occupiedCellsInDirection:Bottom]
- 1); // Don't count yourself twice.
case Horizontal:
return MAX(0, [self occupiedCellsInDirection:Left]
+ [self occupiedCellsInDirection:Right]
- 1); // Don't count yourself twice.
}
}

How to get custom delegate to work

I am creating a custom delegate UIAlertView's alert:buttonClickedAtIndex: method, but it is not working properly. I am subclassing a UIView, and I have two buttons that are tagged as 0 and 1. This still does not work when I go to check the delegate for my custom view. Here the code that I did.
Custom View
- (void) buttonTouchedWithIdentifier:(NSInteger)identifier
{
if (identifier == 0) {
[self.delegate alert:self didClickButtonWithTagIdentifier:0];
}
if (identifier == 1) {
[self.delegate alert:self didClickButtonWithTagIdentifier:1];
}
}
* in my showInViewMethod *
[self.dismissButton addTarget:self action:#selector(buttonTouchedWithIdentifier:) forControlEvents:UIControlEventTouchDown];
[self.continueButton addTarget:self action:#selector(buttonTouchedWithIdentifier:) forControlEvents:UIControlEventTouchDown];
self.dismissButton.tag = 0;
self.continueButton.tag = 1;
* in my view controller *
nextLevelAlert = [[ARAlert alloc] init];
nextLevelAlert.delegate = self;
[nextLevelAlert showInView:self.view
withMessage:[NSString stringWithFormat:#"Congratulations, you have completed level %i.\nWould you like to continue?", levelNumber]
dismissButtonTitle:#"Menu"
continueButtonTitle:#"Next Level"];
- (void)alert:(ARAlert *)alert didClickButtonWithTagIdentifier:(NSInteger)tagId
{
if (alert == nextLevelAlert) {
if (tagId == 0) {
NSLog(#"User does not want to continue.");
}
}
}
Now, nextLevelAlert has the delegate set to self, and I do have the delegate declared in my view controller's class. Also, when i do the showInView... for nextLevelAlert, it DOES appear, it is recognizing what button is being pressed.
My guess is your param is not a NSInteger but the button, you should change buttonTouchedWithIdentifier like this :
- (void) buttonTouchedWithIdentifier:(id)sender
{
UIButton *button = (UIButton*)sender;
NSLog(#"buttonTouchedWithIdentifier %#",#(button.tag));
if (button.tag == 0) {
[self.delegate alert:self didClickButtonWithTagIdentifier:0];
}
if (button.tag == 1) {
[self.delegate alert:self didClickButtonWithTagIdentifier:1];
}
}
Also when comparing two objects use isEqual: instead of ==
- (void)alert:(ARAlert *)alert didClickButtonWithTagIdentifier:(NSInteger)tagId
{
if ([alert isEqual:nextLevelAlert]) {
if (tagId == 0) {
NSLog(#"User does not want to continue.");
}
}
}

How to make one button do two things?

I have a check button and 3 views, one TextField
I'd like the check button to have the ability to know which view its on,
view1 view1 or view 3. so that when the user types in the right answer the specific actions works for that view its on only!
- (IBAction)btncheck:(id)sender {
// Enter has been pressed, see if the text in the textView equals our string
NSString *answer = [_textbox.text stringByReplacingOccurrencesOfString:#"q telecom " withString:#""];
// to block user from getting incorrect answer with no text in text field
if([answer isEqualToString:#""]){
}
else
if ([answer isEqualToString:#"q telecom"]) {
//Name:Q Telecom - FIRST TEXTFIELD SAVED - This will save the answer (q telecom forever to the user) *SAVED
NSString *savestring = _textbox.text; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
// String is correct, resign keyboard, xclear, and protection/shield
_keyboard.hidden = YES;
_textXclear.hidden = YES;
_protectionOutBtn.enabled = NO;
//Perfect button
[_closeone setHidden:NO];
[_wrongone setHidden:YES];
score = MAX (score +100, 1);
[scoreLabel setText:[NSString stringWithFormat:#"Σκορ: %d", score]];
// remeber that coins must always be coins = coins + numeber to add up correctly
coins = coins +5;
if(score == 100) {coins = coins + 3;}
[coinsLabel setText:[NSString stringWithFormat:#"%d", coins]];
//coin animation start
FImageWinfive.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"coindust2.png"],[UIImage imageNamed:#"coindust3.png"],[UIImage imageNamed:#"coindust4.png"],[UIImage imageNamed:#"coindust5.png.png"],[UIImage imageNamed:#"coindust6.png"],[UIImage imageNamed:#"coindust7.png"],[UIImage imageNamed:#"coindust8.png"],[UIImage imageNamed:#"coindust9.png"],[UIImage imageNamed:#"coindust10.png"],[UIImage imageNamed:#"coindust11.png"],[UIImage imageNamed:#"coindust12.png"], nil];
[FImageWinfive setAnimationRepeatCount:1];
FImageWinfive.animationDuration = 1.5;
FImageWinfive.animationRepeatCount = 1;
[FImageWinfive startAnimating];
//coin animation finished
_textbox.enabled = NO;
}
else {
CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:#"position"];
[shake setDuration:0.1];
[shake setRepeatCount:2];
[shake setAutoreverses:YES];
[shake setFromValue:[NSValue valueWithCGPoint:
CGPointMake(shaker.center.x - 5,shaker.center.y)]];
[shake setToValue:[NSValue valueWithCGPoint:
CGPointMake(shaker.center.x + 5, shaker.center.y)]];
[shaker.layer addAnimation:shake forKey:#"position"];
// Was not correct. Notify user, or just don't do anything
[_wrongone setHidden:NO];
score = score -3;
[scoreLabel setText:[NSString stringWithFormat:#"Σκορ: %d", score]];
//SCORE
}
if (score < 100) {
closeonechange.text = #"Σωστά!";
_imageCorP.image = [UIImage imageNamed:#"boxg_25.png"];
} else {
closeonechange.text = #"Αψογα!";
_imageCorP.image = [UIImage imageNamed:#"telioo.png"];
}
There may be an easier way, but here's an option.
First, in the viewController's .m file, a #property:
#interface SomeViewController()
#property (nonatomic, weak) UITextField *activeField;
#end
Now, assume all three of these text fields are delegated by this view controller:
- (void)textFieldDidBeginEditing:(UITextField*)textField {
self.activeField = textField;
}
Now in the method that handles button touch:
- (IBAction)btncheck:(id)sender {
if (self.lastActiveField == self.view1) {
// check view 1
} else if (self.lastActiveField == self.view2) {
// check view 2
} else if (self.lastActiveField == self.view3) {
// check view 3
} else {
// either no field has been selected yet or there are other text fields
// delegated by this view controller
}
}
A slightly better and clearer solution would involve using an enum and setting the text field's tags with this enum, and then in the IBAction, switching on the enum.
For example:
typedef NS_ENUM(NSInteger, ActiveFieldEnum) {
tag_VIEW1 = 100,
tag_VIEW2 = 101,
tag_VIEW3 = 102
};
A property to track the last active button:
#property (nonatomic,assign) ActiveFieldEnum lastActiveField;
Now you can set this in the storyboard or in a life-cycle method of your view controller:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// set up your view
self.view1.tag = tag_VIEW1;
self.view2.tag = tag_VIEW2;
self.view3.tag = tag_VIEW3;
}
The text field delegate:
- (void)textFieldDidBeginEditing:(UITextField*)textField {
self.lastActiveField = textField.tag;
}
And now in the button method:
- (IBAction)btncheck:(id)sender {
switch(self.lastActiveField) {
case tag_VIEW1:
// do stuff
break;
case tag_VIEW2:
// do stuff
break;
case tag_VIEW3:
// do stuff
break;
default:
// same as the final else before
break;
}
}

Go back to previous UITextfield , IOS

My app has a registration view, I compare strings in password textfield and confirm password textfield , if they dont match I want user go back to password textfield
This question done it with using tags
UITextField jump to previous
Is there a way to accomplish this without using tags?
//call next textfield on each next button
- (BOOL) textFieldShouldReturn:(UITextField *) textField {
BOOL didResign = [textField resignFirstResponder];
if (!didResign) return NO;
if ([textField isKindOfClass:[SOTextField class]])
dispatch_async(dispatch_get_current_queue(),
^ { [[(SOTextField *)textField nextField] becomeFirstResponder]; });
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField==self.confirmPassword) {
if ([self.password.text isEqualToString:self.confirmPassword.text]) {
NSLog(#"password fields are equal");
}
else{
NSLog(#"password fields are not equal prompt user to enter correct values");
//[self.password becomeFirstResponder]; doesnt work
}
}
}
Without using tags, you could create an NSArray of textfield outlets the describes the desired ordering.
Declare and init like this ...
#property(nonatomic,strong) NSArray *textFields;
- (NSArray *)textFields {
if (!_textFields) {
// just made these outlets up, put your real outlets in here...
_textFields = [NSArray arrayWithObjects:self.username, self.password, nil];
}
return _textFields;
}
You'll need to fetch the text field that currently has focus, if there is one...
- (UITextField *)firstResponderTextField {
for (UITextField *textField in self.textFields) {
if ([textField isFirstResponder]) return textField;
}
return nil;
}
Then advance focus like this...
- (void)nextFocus {
UITextField *focusField = [self firstResponderTextField];
// what should we do if none of the fields have focus? nothing
if (!focusField) return;
NSInteger index = [self.textFields indexOfObject:textField];
// advance the index in a ring
index = (index == self.textFields.count-1)? 0 : index+1;
UITextField *newFocusField = [self.textFields objectAtIndex:index];
[newFocusField becomeFirstResponder];
}
And move focus backward like this...
- (void)previousFocus {
UITextField *focusField = [self firstResponderTextField];
// what should we do if none of the fields have focus? nothing
if (!focusField) return;
NSInteger index = [self.textFields indexOfObject:textField];
// backup the index in a ring
index = (index == 0)? self.textFields.count-1 : index-1;
UITextField *newFocusField = [self.textFields objectAtIndex:index];
[newFocusField becomeFirstResponder];
}

Resources