Better way to get button setTitle? - ios

Currently I am doing this:
NSInteger senderTag = [sender tag];
But all I really want is the title/value of the button pressed not the tag id.

You can get the text of your button's label by checking
NSString *txt = [sender titleLabel].text;
This is not as reliable as the tag, though, especially when your app changes the text on the label in response to user interactions or due to selection of a new locale.
Also note that to set the label you need to use a different method:
[sender setTitle:#"Hello" forState:UIControlStateNormal];

Related

How to set a button tag to an array of arrays entry point

I need some help. I'm currently learning objective c and I'm trying to do the following:
Add to story board a button(action) textfield & label(checked)
type in a number in the text field press the button=>create o a new row a new button with as many text field as requested previously.(checked)
Store each new button+ it's text fields into an array, then store that array in a new array, rows and columns[0][0] etc style(checked)
Add for each new button I create a tag and use array count method for it to identify my button(checked). I do this because each array looks like this [0]button[1]textfield[2]textfield and so on with only textfields following.
Now here is my code to create my button:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(_x, _y, 100.0, 30.0);
[button setTitle:#"Calculate" forState:UIControlStateNormal];
button.tag = [_arayOfArays count];
[button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
And this is my method that calls it:
-(void)myAction:(UIControl*)sender{
if ([[_arayOfArays objectAtIndex:sender]count] == 4) {
//here i call another method that calculates the area of a triangle if the button I would press would be in a same array with another 3 text fields
}
Now my problem is that my sender address memory always points to [0][0] or [1][0] and so on depending on what i pressed, and I want it to point to [0] or [1] and so on so I can use the count method.
Can anyone please give me a hint on how I achieve this? Thanks and sorry for the long post.
You probably mean to access the element at index specified by the buttons tag like this:
[_arayOfArays objectAtIndex:sender.tag]

Apple Watch get button title on IBAction

I tried all the options for iPhone, to get the title of a button on click, but none of them works on Watch Simulator.
So far, I tried:
• NSString *senderTitle = [sender titleForState:UIControlStateNormal];
• NSString *title = [(UIButton *)sender currentTitle];
• UIButton * button = (UIButton *)sender;
NSString *title = [[button titleLabel] text];
• UIButton *button = (UIButton *)sender;
NSString *title = button.currentTitle;
Any suggestions, please?
WatchKit doesn't include a sender with button actions and even if it did there is no way to get the current title from a WKInterfaceButton. If you need to know the title of the button you should have a different action for each of your buttons so you know which button was pressed to cause the action.
If you want to change the title of a button on a tap in WatchKit it is very simple.
-(IBAction)changebuttontitle:(id)sender {
[self.button setTitle:#"button title here"];
}
In WatchOS2 this is
buttonOutlet.setTitle("David Bowie")
and also note that you cannot change the button title color. For that you will need to create a an identical button with a custom title color in PS then swap the image using
setBackgroundImage(image: UIImage?)

Changing the text of a label on button press with dynamic integer

I'm following a tutorial to create a simple game where you tap a button and the the game counts how many times you have pressed the button as you go along. The score is displayed on screen in the form of a label.
I can make it so that when you press the button the label text changes to say 'Pressed!'. But then i can not get the label to change when i try to add the changing score with a format specifier.
-(IBAction)buttonPressed{
count ++;
//scoreLabel.text =#"pressed";
scoreLable.text = [NSString stringWithFormat:#"Score\n%i", count];
}
Any help would be greatly appreciated. Thanks!
You may not have your label set up for multiple lines of text. Try getting rid of the "\n" in your format string. Other than that, you need to tell us what happens. Have you put a breakpoint to make sure your button IBAction is being called? Have you checked to make sure "scoreLable" (sic) is not nil? The devil is in the details.
-(IBAction)buttonPressed : (id) sender{
UIButton * btnPressed = (UIButton *)sender;
int buttonValue = [[btnPressed titleForState:UIControlStateNormal] intValue];
NSLog(#"Button value = %d", buttonValue);
//scoreLabel.text =#"pressed";
scoreLable.text = [NSString stringWithFormat:#"Score\n%i", count];
}
First You Can Set static int count = 0;

iOS: I set my uibuttons with tags. How do I change the specific button image based on its tag?

I have a multiple array of buttons called button. Each one is tagged. How do I change the image on the button based on its tag and tag only. As of right now, it only changes the very last button.
-(void)buttonTapped:(id)sender{
NSLog (#"%i",[sender tag])];
[button setImage:[UIImage imageNamed:#"button_change.png"] forState:UIControlStateNormal];
}
Either:
for (UIButton *btn in button) {
if(btn.tag == 1)
{
// do something
break; // don't need to run the rest of the loop
}
}
if you want to use the array (it shouldn't be called 'button', use something with a plural for an array)
or an easier way:
UIButton *btn = (UIButton *)[self.view viewWithTag:1];
However a much simpler way would be to use the param in the callback (unless thats not the button you want). Like so:
-(void)buttonTapped:(id)sender
{
UIButton *tappedBtn = (UIButton *)sender;
[tappedBtn setImage:[UIImage imageNamed:#"button_change.png"] forState:UIControlStateNormal];
}
If you just want to change the button that was tapped the following should work.
-(void)buttonTapped:(id)sender
{
NSLog (#"%i",[sender tag])];
UIButton *tappedButton = (UIButton *)sender;
[tappedButton setImage:[UIImage imageNamed:#"button_change.png"] forState:UIControlStateNormal];
}
If you want to change other buttons then you can retrieve the buttons using
[self.view viewWithTag:1000]; //1000 is the tag you assigned
You don't really need to use tags in the this case. When an IBAction is invoked, the sender parameter is a pointer to the control that triggered the IBAction. (Your button.)
Thus, you already have a pointer to the button.
So, as others have pointed out, your code could read like this:
-(void)buttonTapped:(UIButton *)sender
{
[sender setImage:[UIImage imageNamed:#"button_change.png"] forState:UIControlStateNormal];
}
Note that I changed the type of sender to UIButton so that you don't have to cast it. As long as the action is only ever connected to a button, this is safe to do and makes the code cleaner.
As the other poster pointed out, having an array of buttons called "button" is bad. I renamed it to "buttons" in the code below:
If you wanted to do it using tags and an array of buttons, you could use code like this:
-(void)buttonTapped:(UIButton *)sender
{
NSUInteger tag = [sender tag];
UIButton *aButton = buttons[tag];
[aButton setImage:[UIImage imageNamed:#"button_change.png"] forState:UIControlStateNormal];
}
Create images with names button_change1.png, button_change2.png, etc.
And:
-(void) buttonTapped:(UIButton*)sender
{
NSString* imageName = [NSString stringWithFormat: #"button_change%ld.png", (long)sender.tag];
[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}

How to Change textLabel property in UIButton programmatically in iOS?

I have a UIButton that should have 2 statuses - "Play" and "Pause"; i.e. - at the first time the user sees it it says "Play" and then whenever the user clicks it it should switch between "Play" and "Pause".
I managed to create the controller itself - the content is played and paused properly - but I cannot seem to change the UIButton Text Label text.
I use:
myButton.titleLabel.text = #"Play";
myButton.titleLabel.text = #"Pause";
It's not working. The text is not changing. I also tried [myButton.titleLabel setText:#"Pause"] and it's not working as well.
How can I set it?
It should be:
[myButton setTitle:#"Play" forState:UIControlStateNormal];
You need to pass the state as well. You can check other state's here.
You can then do something like this:
[myButton setTitle:#"Play" forState:UIControlStateNormal];
[myButton setTitle:#"Stop" forState:UIControlStateSelected];
SWIFT 4
myButton.setTitle("Pause", for: .normal)
I found this to be somewhat out of date since attributed strings were added. Apparently titles of buttons assigned in a storyboard are attributed strings. Attributed titles take precedence over NSString titles, so if you want to use a simple string as a title you have to remove the attributed title first. I did as below, though there may be a better way. You could, of course, make your new title also an attributed string.
[myButton setAttributedTitle: nil forState: 0xffff];
[myButton setTitle: #"Play" forState: UIControlStateNormal];
And if you want to load it on page load, and support localized language:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.flagToChangeLabel){
NSString* newBtnTitle = NSLocalizedString(#"LOCALIZED_KEY", nil);
[self.laterButton setTitle:newBtnTitle forState:UIControlStateNormal];
[self.laterButton setTitle:newBtnTitle forState:UIControlStateSelected];
}
}

Resources