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;
}
}
Related
I have a fairly bog-standard UI with a text field embedded in a few subviews. I'm seeing an issue where I can't move the cursor once I've typed in the text field, it continually just moves back to the start of the input.
At no point anywhere in the code are any methods called to change the editing position, like setSelectedTextRange or similar.
Please excuse the Objective-C, this is a legacy codebase!
self.textField = [UITextField new];
self.textField.text = element.value;
self.textField.placeholder = element.placeholder;
self.textField.returnKeyType = UIReturnKeyNext;
self.textField.delegate = self;
self.textField.autocorrectionType = element.autocorrectionType;
self.textField.autocapitalizationType = element.autocapitalizationType;
self.textField.secureTextEntry = element.secureTextEntry;
self.textField.keyboardType = element.keyboardType;
[self.textField addTarget:self action:#selector(handleTextChange:) forControlEvents:UIControlEventEditingChanged];
[self addSubview:self.textField];
- (void)handleTextChange:(UITextField *)sender
{
self.inputElement.value = sender.text;
// If we're showing the validation warning, give real time feedback to user
if (self.isShowingValidationWarning) {
[self validate];
}
}
- (void)validate
{
BOOL isValid = self.inputElement.isValid;
[self showValidationHint:!isValid animated:YES];
}
- (void)showValidationHint:(BOOL)show animated:(BOOL)animated
{
self.isShowingValidationWarning = show;
CGFloat duration = 0.0;
if (animated) {
duration = 0.2;
}
[UIView animateWithDuration:duration animations:^{
if (show) {
self.characterCountLabel.alpha = 0.0;
self.validationButton.alpha = 1.0;
self.validationButton.transform = CGAffineTransformMakeScale(1.0, 1.0);
} else {
self.characterCountLabel.alpha = 1.0;
self.validationButton.alpha = 0.0;
self.validationButton.transform = CGAffineTransformMakeScale(0.1, 0.1);
}
}];
}
inputElement.value doesn't have a setter or getter function, so nothing funky going on there!
The answer here was exactly what #juanreyesv pointed out in the comments! becomeFirstResponder call was moved to viewDidAppear rather than viewWillAppear and now it's working!
I'm making my second game on XCode and there seems to be something wrong with the code. It's a space shooter game where the playership follows your finger and you tap to release the missile. The problem is... when I press 'start game', everything is hidden and will not popup. Here is my viewcontroller.h and viewcontroller.m
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
int score;
int lives;
int enemyAttackOccurence;
int enemyPosition;
int randomSpeed;
float enemySpeed;
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#implementation PlayViewController
-(void)viewDidAppear:(BOOL)animated {
// Images that are to be hidden
playerShip.hidden = YES;
enemyShip.hidden = YES;
missile.hidden = YES;
earth.hidden = YES;
// Hidden Labels
scoreLabel.hidden = YES;
livesLabel.hidden = YES;
// Set score and lives remaining
score = 0;
lives = 0;
// Strings
scoreString = [NSString stringWithFormat:#"Score: 0"];
liveString = [NSString stringWithFormat:#"Lives: 0"];
// Initial Label Text
scoreLabel.text = scoreString;
livesLabel.text = liveString;
// Image starting positions
playerShip.center = CGPointMake(150, 658);
enemyShip.center = CGPointMake(175, 20);
missile.center = CGPointMake(playerShip.center.x, playerShip.center.y);
}
-(IBAction)startGame:(id)sender {
// Hide buttons
startButton.hidden = YES;
exitButton.hidden = YES;
// Images to show
playerShip.hidden = NO;
enemyShip.hidden = NO;
earth.hidden = NO;
// Labels
scoreLabel.hidden = NO;
livesLabel.hidden = NO;
[self positionEnemy];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view];
playerShip.center = CGPointMake(point.x, playerShip.center.y);
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[missileMovementTimer invalidate];
missile.hidden = NO;
missile.center = CGPointMake(playerShip.center.x, playerShip.center.y);
missileMovementTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(missileMovement) userInfo:nil repeats:YES];
}
-(void)positionEnemy {
// Random enemy position
enemyPosition = arc4random() % 249;
enemyPosition = enemyPosition + 20;
// Enemy Image Location
enemyShip.center = CGPointMake(enemyPosition, -40);
// Set enemy speed
randomSpeed = arc4random() % 3;
switch (randomSpeed) {
case 0:
enemySpeed = 0.03;
break;
case 1:
enemySpeed = 0.02;
break;
case 2:
enemySpeed = 0.01;
default:
break;
}
enemyAttackOccurence = arc4random() % 5;
[self performSelector:#selector(enemyMovementTimerMethod) withObject:nil afterDelay:enemyAttackOccurence];
}
-(void)enemyMovementTimerMethod {
enemyMovementTimer = [NSTimer scheduledTimerWithTimeInterval:enemySpeed target:self selector:#selector(enemyMovement) userInfo:nil repeats:YES];
}
-(void)enemyMovement {
enemyShip.center = CGPointMake(enemyShip.center.x, enemyShip.center.y + 2);
if (CGRectIntersectsRect(enemyShip.frame, earth.frame)) {
lives = lives - 1;
liveString = [NSString stringWithFormat:#"Lives: %i", lives];
livesLabel.text = liveString;
// Stop Enemy Moving
[enemyMovementTimer invalidate];
if (lives > 0) {
[self positionEnemy];
}
if (lives == 0) {
[self gameOver];
}
}
}
-(void)missileMovement {
missile.hidden = NO;
missile.center = CGPointMake(missile.center.x, missile.center.y - 2);
if (CGRectIntersectsRect(missile.frame, enemyShip.frame)) {
score = score + 1;
scoreString = [NSString stringWithFormat:#"Score: %i", score];
scoreLabel.text = scoreString;
// Stop missile
[missileMovementTimer invalidate];
// Position missile to be at the playerShip's center
missile.center = CGPointMake(playerShip.center.x, playerShip.center.y);
missile.hidden = YES;
// Stop enemy movement
[enemyMovementTimer invalidate];
[self positionEnemy];
}
}
-(void)gameOver {
[enemyMovementTimer invalidate];
[missileMovementTimer invalidate];
[self performSelector:#selector(gameReplay) withObject:nil afterDelay:3];
}
-(void) gameReplay {
// Images that are to be hidden
playerShip.hidden = YES;
enemyShip.hidden = YES;
missile.hidden = YES;
earth.hidden = YES;
// Hidden Labels
scoreLabel.hidden = YES;
livesLabel.hidden = YES;
// Set score and lives remaining
score = 0;
lives = 0;
// Strings
scoreString = [NSString stringWithFormat:#"Score: 0"];
liveString = [NSString stringWithFormat:#"Lives: 0"];
// Initial Label Text
scoreLabel.text = scoreString;
livesLabel.text = liveString;
// Image starting positions
playerShip.center = CGPointMake(150, 658);
enemyShip.center = CGPointMake(175, 20);
missile.center = CGPointMake(playerShip.center.x, playerShip.center.y);
}
#end
ViewController.h (Just for backup)
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
IBOutlet UIButton *startGame;
}
#end
#interface PlayViewController : UIViewController {
IBOutlet UIImageView *playerShip;
IBOutlet UIImageView *enemyShip;
IBOutlet UIImageView *missile;
IBOutlet UIImageView *earth;
IBOutlet UILabel *livesLabel;
IBOutlet UILabel *scoreLabel;
IBOutlet UIButton *startButton;
IBOutlet UIButton *exitButton;
UITouch *touch;
NSString *liveString;
NSString *scoreString;
NSTimer *enemyMovementTimer;
NSTimer *missileMovementTimer;
}
-(IBAction)startGame:(id)sender;
#end
I am watching a tutorial for this game, the person who created doesn't reply. Please help -- I cannot be any more specific. It just must be a weird gap in the code. Thanks.
Also, you have an IBOutlet and IBAction set for your StartGame button. The IBOutlet you never seem to use. You could be confusing your compiler by having the same name for the UIButton's IBOutlet and IBAction. Remove the IBOutlet, or change the name properly and see if that changes anything.
I'd recommend messing with your lines of code where you are setting object.hidden = YES and object.hidden = NO and see what happens. Often times tampering and testing your code is a good way to see what is going on. Make sure images are set for your UIImageViews. I'm assuming they are set in your interface builder because i don't see where you set them in your code. If there is no image set for the UIImageViews they will be see-through unless given a specific color. If tampering with the code doesn't work it won't hurt to re-watch the tutorial and make sure you didn't mess anything up. Often times the tutorials we watch are out-dated and we are left to solve a small problem ourselves and this may or may not be one of those instances. Again though, test your code and see if things are actually being set to hidden or not when you press that button.
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)];
}
I have 3 UIButton on the same tab.
The problem :
When I click on button1, button2 and button3 all of them got selected; however what I want is when I select (for example) button2, the other buttons be unselected (like radio buttons on html).
Any idea on how I can solve this issue ?
Here is my code :
- (IBAction)button1:(UIButton *)sender {
sender.selected = !sender.selected;
}
- (IBAction)button2:(UIButton *)sender {
sender.selected = !sender.selected;
}
- (IBAction)button3:(UIButton *)sender {
sender.selected = !sender.selected;
}
There are a couple of straightforward solutions. Maybe they are not optimal, but you can use them:
First solution:
Link your buttons with corresponding properties:
#property (weak, nonatomic) IBOutlet UIButton *button1;
#property (weak, nonatomic) IBOutlet UIButton *button2;
#property (weak, nonatomic) IBOutlet UIButton *button3;
In each action change the selected property for each button:
- (IBAction)button1Clicked:(UIButton *)sender {
_button1.selected = YES;
_button2.selected = NO;
_button3.selected = NO;
}
Second solution:
Add all your buttons in NSArray:
NSArray *buttonsArray = [[NSArray alloc] initWithObjects: button1, button2, button3, nil];
Then link all the buttons with one action:
- (IBAction)buttonClicked:(UIButton *)sender {
for (UIButton *btn in _buttonsArray) {
if (btn == sender)
btn.selected = YES;
else
btn.selected = NO;
}
}
Don't forget to make your NSArray accessible for all the methods of the class, for example by creating a corresponding property:
#property (weak, nonatomic) NSArray *buttonsArray;
Third solution:
You can change the tag property for each button (through Interface Builder or in code):
_button1.tag = 1;
_button2.tag = 2;
_button3.tag = 3;
Then link all the buttons with one action (just like in previous example):
- (IBAction)buttonClicked:(UIButton *)sender {
if (sender.tag == 1) {
_button1.selected = YES;
_button2.selected = NO;
_button3.selected = NO;
} else if (sender.tag == 2) {
_button1.selected = NO;
_button2.selected = YES;
_button3.selected = NO;
} else if (sender.tag == 3) {
_button1.selected = NO;
_button2.selected = NO;
_button3.selected = YES;
}
}
Fourth solution: (by #velmurugan-s)
Use one action for all the buttons and set their default state to selected = NO:
- (IBAction)buttonClicked:(UIButton *)sender {
_button1.selected = NO;
_button2.selected = NO;
_button3.selected = NO;
sender.selected = YES;
}
Summary:
I'd recommend you to use the second solution as the most optimal one.
What you can do is connect button1,button2,button3 to same button123 in interface section give them appropriate tags
- (IBAction)button123:(UIButton *)sender;
In its description use below code
- (IBAction)button123:(UIButton *)sender {
if (sender.tag == 111)
{
sender.selected = !sender.selected;
if (sender.selected)
{
self.button2.selected = NO;
self.button3.selected = NO;
}
}
else if (sender.tag == 222)
{
sender.selected = !sender.selected;
if (sender.selected)
{
self.button1.selected = NO;
self.button3.selected = NO;
}
}
else if (sender.tag == 333)
{
sender.selected = !sender.selected;
if (sender.selected)
{
self.button1.selected = NO;
self.button2.selected = NO;
}
}
- (IBAction)button1:(UIButton *)sender {
btn1.selected = YES;
btn2.selected = NO;
btn3.selected = NO;
}
- (IBAction)button2:(UIButton *)sender {
btn1.selected = NO;
btn2.selected = YES;
btn3.selected = NO;
}
- (IBAction)button3:(UIButton *)sender {
btn1.selected = NO;
btn2.selected = NO;
btn3.selected = YES;
}
You had change the selected sate for a button that you have selected,You need to change all other button state too.
I took this project from github.
It is custom AlertView. I understood how it works. Modified it for my project, like this
Course1 - name of some product, and '1' - is its amount. When I'm typing on plus/minus amount increases/decreases. But it works only for my variable (which I load on this AlertView, when I show it, and it is 1). How can I reload message of this alert view with changing var (amount). I can't understand.
Here my code.
In my class I call alert view by this code
BlockAlertView *alert = [BlockAlertView alertWithTitle: title message:ac.acCount];
[alert setCancelButtonWithTitle:#"-" block:nil];
[alert setDestructiveButtonWithTitle:#"+" block:^{
int u = [ac.acCount intValue];
u++;
ac.acCount = [NSString stringWithFormat:#"%d", u];
NSLog(#"%d", u);
}];
[alert addButtonWithTitle:#"Ok" block:^{
NSMutableArray *container = [[NSMutableArray alloc] init];
[container addObject:title];
[container addObject:price];
[container addObject:bId];
[container addObject:ac.acCount];
[container addObject:depid];
[[NSNotificationCenter defaultCenter] postNotificationName:#"MyNotification" object:container];
}];
[alert show];
Show method just draws alert view with params which takes from alertWithTitle: title message:ac.acCount. Here is the code
+ (BlockAlertView *)alertWithTitle:(NSString *)title message:(NSString *)message
{
return [[[BlockAlertView alloc] initWithTitle:title message:message] autorelease];
}
here is
- (id)initWithTitle:(NSString *)title message:(NSString *)message
{
NSLog(#"title - %# message - %#", title, message);
if ((self = [super init]))
{
UIWindow *parentView = [BlockBackground sharedInstance];
CGRect frame = parentView.bounds;
frame.origin.x = floorf((frame.size.width - background.size.width) * 0.5);
frame.size.width = background.size.width;
_view = [[UIView alloc] initWithFrame:frame];
_blocks = [[NSMutableArray alloc] init];
_height = kAlertViewBorder + 6;
if (title)
{
CGSize size = [title sizeWithFont:titleFont
constrainedToSize:CGSizeMake(frame.size.width-kAlertViewBorder*2, 1000)
lineBreakMode:UILineBreakModeWordWrap];
UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(kAlertViewBorder, _height, frame.size.width-kAlertViewBorder*2, size.height)];
labelView.font = titleFont;
labelView.numberOfLines = 0;
labelView.lineBreakMode = UILineBreakModeWordWrap;
labelView.textColor = kAlertViewTitleTextColor;
labelView.backgroundColor = [UIColor clearColor];
labelView.textAlignment = UITextAlignmentCenter;
labelView.shadowColor = kAlertViewTitleShadowColor;
labelView.shadowOffset = kAlertViewTitleShadowOffset;
labelView.text = title;
[_view addSubview:labelView];
[labelView release];
_height += size.height + kAlertViewBorder;
}
if (message)
{
CGSize size = [message sizeWithFont:messageFont
constrainedToSize:CGSizeMake(frame.size.width-kAlertViewBorder*2, 1000)
lineBreakMode:UILineBreakModeWordWrap];
UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(kAlertViewBorder, _height, frame.size.width-kAlertViewBorder*2, size.height)];
labelView.font = messageFont;
labelView.numberOfLines = 0;
labelView.lineBreakMode = UILineBreakModeWordWrap;
labelView.textColor = kAlertViewMessageTextColor;
labelView.backgroundColor = [UIColor clearColor];
labelView.textAlignment = UITextAlignmentCenter;
labelView.shadowColor = kAlertViewMessageShadowColor;
labelView.shadowOffset = kAlertViewMessageShadowOffset;
labelView.text = message;
[_view addSubview:labelView];
[labelView release];
_height += size.height + kAlertViewBorder;
}
_vignetteBackground = NO;
}
return self;
}
I tried to use something like this
-(void)reloadAlertView: (NSString *) title: (NSString *) message{
[self initWithTitle:title message:message];
}
and call this from my class, where i shows alert view.
[alert reloadAlertView: title: newMessage];
YOu need to ref a new label in your CustomAlertView.h
#property (nonatomic, strong) IBOutlet UILabel *mylab;
then you can get the properties of this label by the object of the CustomAlertView.h class
BlockAlertView *alert ...;
alert.mylab.text = #"hello";
solution (simple , not required to hack the BlockAlertView.m)
whenever the + button is click, the alert will be disappeared, and reappeared again.
ViewController.m
#implementation ViewController {
BlockAlertView *alert ;
NSInteger value;
}
-(void) viewDidLoad {
value = 0;
[self reloadAlert];
}
-(void) reloadAlert {
value += 1;
__block ViewController* _self = self;
alert = [[BlockAlertView alloc] initWithTitle:#"Course1" message:[[[NSNumber alloc] initWithInteger:value ] stringValue]];
[alert setDestructiveButtonWithTitle:#"PLUS" block:^{
[_self reloadAlert];
}];
[alert show];
}
}
solution , if you want to keep the AlertView remained, without popping up.
a. Modify BlockAlertView.h to bring messageLabelView outside to be accessed from ViewController, so we can redraw the message later.
BlockAlertView.h
#interface BlockAlertView {
...
}
#property (nonatomic, retain) UILabel *messageLabelView;
You can also bring the UIView *_view out of #protected and into #property instead, if preferred. In that case, messageLabelView can be access via _view 's subviews
b. Modify BlockAlertView.m dismissWithClickedButtonIndex:animated: to disable removeView function from being called if buttonIndex == PLUS sign button - buttonIndex to be hardcoded to 0.
There may be a better option to stop the execution thread inside the block obj of PLUS button, but I dont know how to do :)
c. Modify BlockAlert.m initWithTitle:message: to add reference of messageLabelView into labelView during the render of message Label.
BlockAlertView.m
#synthesize messageLabelView;
- (id)initWithTitle:(NSString *)title message:(NSString *)message
{
...
// code to initialize messageLabelView
if (message)
{
....
// code to render labelView for message. add reference to messageLabelView
messageLabelView = labelView;
// [labelView release];
}
}
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated
{
if (buttonIndex >= 0 && buttonIndex < [_blocks count])
{
id obj = [[_blocks objectAtIndex: buttonIndex] objectAtIndex:0];
if (![obj isEqual:[NSNull null]])
{
((void (^)())obj)();
}
}
// there may be a better option to stop the execution thread inside the block obj above
if(buttonIndex == 0) {// or whatever index of Plus Button, dont removeView
return;
}
// code to removeView below, keep as usual
if (animated)
{
...
}
else
{
....
}
}
}
d. Change reloadAlert in ViewController.m
ViewController.m
-(void) reloadAlert {
value += 1;
alert.messageLabelView.text = [[[NSNumber alloc] initWithInteger:value ] stringValue];
[alert.messageLabelView setNeedsDisplay];
}