Change text for a UIButton - ios

I´m making a quiz game, and I want buttons to show the answer alternatives for the question..
I know how to do it if I use label.text but how can I do the same just with a button?
Please help! thanks

[button setTitle:#"New Title" forState:UIControlStateNormal];
easy to see this from apples docs

You set the title text of the button:
[button setTitle:#"Answer 1" forState:UIControlStateNormal];

Try with this:
yourButton.titleLabel.text = #"";

Related

extract UIButton object from NSString

I want to hide already created UIButton object of same name as contents of string myBtnName
NSString *str=#"first";
NSString *myBtnName=[str stringByAppendingString:#"Btn"];
myBtnName is (NSString ) and has value of #"firstBtn"... How do i make it (UIButton) firstBtn ?... Please Help
don't under stand your question properly but i get your problem little bit. that you want to set title of button by appending your variable try this:
this will append your text i.e #"Btn" with your variable: hope this helps.. :)
UIButton *btn = [btn setTitle:[NSString stringWithFormat:#"%#Btn",yourVariableString] forState:UIControlStateNormal];
UIButton *button = [button setTitle:[NSString stringWithFormat:#"%#Btn",yourVariableString] forState:UIControlStateNormal];
You question is unclear to me, but if you want to get a button that you defined as a property by it's name you can use this:
NSString* myBtn = [str stringByAppendingString:#"Btn"];
UIButton* button = [self valueForKey:myBtn];

UIButton title text is not updated even if I update it in Main thread

I'm trying to change the title of an UIButton I've created programmatically, when the user clicks in it. So, this is my code to create the UIButton:
myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)];
[myButton setBackgroundColor:[UIColor blackColor]];
[myButton setAlpha:0.7];
[myButton setTitle:#"Hello" forState:UIControlStateNormal];
[myButton addTarget:self action:#selector(userClicked:) forControlEvents:UIControlEventTouchUpInside];
[parentView addSubview:myButton];
And, in my userClicked: method, I do:
-(void) userClicked:(UIButton*)button
{
NSLog(#"USER CLICKED!!!");
if ([NSThread isMainThread])
{
NSLog(#"is main thread");
}
[button setTitle:#"Bye" forState:UIControlStateHighlighted];
[button setTitle:#"Bye" forState:UIControlStateNormal];
[button setTitle:#"Bye" forState:UIControlStateSelected];
[self someLengthyComputation];
}
The weird thing is that I can see the log messages printed:
USER CLICKED!!!
isMainThread
But, the title of the button does not change! What am I doing wrong?
EDIT: Setting the title for several states doesn't work either.
EDIT2: If I print the description of button in the debugger window of Xcode, it shows the right title!
Printing description of button->_titleView:
<UIButtonLabel: 0xa4c9310; frame = (95 216; 130 22); text = 'Bye'; clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xa44f080>>
This worked for me to update the title text (iOS 7.1, Xcode 5.1):
button.enabled = FALSE;
[button setTitle:#"Test" forState:UIControlStateNormal];
button.enabled = TRUE;
I was having the same problem, and I noticed that everywhere else I was setting the attributedTitle. So any updates to the title were not affecting the attributed title.
My solution:
[button setAttributedTitle:#"" forState:UIControlStateNormal];
instead of
[button setTitle:#"" forState:UIControlStateNormal];
At the moment, the shortest work around I came with is calling:
[button setNeedsLayout];
After updating the title.
This seems to happen in iOS 7.1.
All my buttons, which were behaving correctly in previous iOS versions (or maybe just compiled with previous SDKs) suddenly stopped doing that when compiled in Xcode 5.1.1 SDK 7.1.
Looks like Apple's bug.
I had a similar problem using storyboards. Using the answers above I had to use
[mybutton setTitle:#"SomeText" forState:UIControlStateNormal];
[button setNeedsLayout];
[button layoutIfNeeded];
AND I had to make sure that the button type was 'Custom' not 'System' in the attributes inspector.
Please see if this might help you...when the button is clicked check for condition if buttonToggled...like below when you have a function like changeButtonText
-(IBAction)changeButtonText:(id)sender {
if (!buttonToggled) {
[sender setTitle:#"Initial Text" forState:UIControlStateNormal];
buttonToggled = YES;
} else {
[sender setTitle:#"Alternative Text" forState:UIControlStateNormal];
buttonToggled = NO;
}
}
There are several issues in your code:
You are assigning callback to the button:
#selector(userClicked:)
but your code is in another method:
-(void)userTapOnTapToRefreshView:(UIButton*)button
To fix that you need to implement something like this:
-(void)userClicked:(id)sender
{
[(UIButton*)sender setTitle:#"Bye" forState:UIControlStateNormal];
}
Also this part of code does not make sense for me:
[parentView myButton];
Try to change it to:
[parentView addSubview:myButton];
Hope it will help :)
For Swift 3 to 5 just use the following:
button.setTitle("My title", for: .normal)
or for a attributed text use this:
button.setAttributedTitle(<AttributedString>, for: .normal)
This is kinda late and somewhat relates to Walter Schurter's response:
I had a similar issue where my button text was being set correctly until I updated to 7.1. Then I found that since my button was disabled, I had to set the title color and title text for the disabled state to get the text to show up. Then everything worked like a charm!
In iOS 7, UIButton's title is not updated when it is disabled. It seems like a bug on iOS 7.
As a workaround, update both normal and disabled title. It works!
[button setTitle:title forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateDisabled];
Try this:
[button setTitle:#"Bye" forState:UIControlStateHighlighted];
or:
[button setTitle:#"Bye" forState:UIControlStateSelected];
You could also modify your void function:
-(void) userClicked
{
NSLog(#"USER CLICKED!!!");
if ([NSThread isMainThread])
{
NSLog(#"is main thread");
}
[myButton setTitle:#"Bye" forState:UIControlStateNormal];
}
In my case I tried everything but nothing was working.
Then I just changed button type from system to custom from storyboard. BOOM! everything started behaving normally.
Change the button type to 'Custom', instead of 'System' and it will work as expected :)
Well, is all about the enabled state of a UIButton, Apple has changed something in 7.1 that does not allow you to change the title if you have the UIButton on a disabled state, thats all.
Thanks Apple, i have lost 10 min. debuging an app that was working fine.
Just found out this morning, got updated XCode yesterday to the 5.1.1 and iOS to 7.1
It could be the button layout refresh issue.....
Try using...
[button setNeedsLayout];
[button layoutIfNeeded];
It will force button to update the layout.
Finally, I've figured it out. There were two problems:
1) button was not in state UIControlStateNormal.
2) I was calling a method performing a long computation just after setting the title, [self someLengthyComputation].
I've solved the problem by:
1) Setting the title for all states of the button.
2) Performing that big computation in another thread, not the main thread.
My working code now is:
-(void) userClicked:(UIButton*)button
{
NSLog(#"USER CLICKED!!!");
if ([NSThread isMainThread])
{
NSLog(#"is main thread");
}
[button setTitle:#"Bye" forState:UIControlStateHighlighted];
[button setTitle:#"Bye" forState:UIControlStateNormal];
[button setTitle:#"Bye" forState:UIControlStateSelected];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
[self someLengthyComputation];
});
}
Thank you very much to everybody who has answered/commented!
This may be trivial, but if you set some button image (instead of background image) which fills the whole button frame, this will shift the title right and thus make it invisible.
If so, try changing button image to background image.
Per Apple developer guide, you should not set either the button title label text or color directly as a property (for example, do not do this: myButton.titleLabel.text=#"SomeText" or myButton.titleLabel.textColor=[UIColor blackColor]).
Rather, you set them using the UIButton setter functionality, like this:
[myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
...or like this:
[myButton setTitle:#"SomeText" forState:UIControlStateNormal];.
See the Apple guide.
Conclusion after trying many solutions is to use setAttributedTitle instead of setTitle.
To make the title string for AttributedString:
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:#" new Test "];
[button setAttributedTitle:attString forState:UIControlStateNormal];
By the way, this problem is not occasionally happen in normal but it suddenly happen mainly for the following reasons:
If you change the enabled state of a UIButton and try to change the title.
If you use an attributed value and then want to change it using setTitle, the attributed value is superior to the title in that case.
If you navigate to another view controller and then return back to update the button title.
There is no requirement to use:
[button setNeedsLayout];
[button layoutIfNeeded];
Instead, first set type as DEFAULT to CUSTOM
If you applied setAttributedTitle then use:
[button setAttributedTitle:[NSAttributedString new] forState:UIControlStateNormal];
Otherwise there is no need to change anything.
If the color of the text has not changed then apply same thing and set title color with:
[button setTitleColor:[any_color] forState:UIControlStateNormal];
None of the above worked for my case (I was having a button on top of a view presented with UIPopoverController), and I had to removeFromSuperview before setTitle, then addSubview back - hope this helps someone with similar issues
I doubt if 'button' passed in as a parameter is myButton.Anyway,if myButton is a member var,you can just [myButton setTitle:#"Bye" forState:UIControlStateNormal];
Try to declare you button as a property, either in the interface or in the implementation part of you view / view controller
#property(nonatomic,strong) UIButton* myButton;
then create it
self.myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)];
[_myButton setBackgroundColor:[UIColor blackColor]];
...
It should work. Don't ask me why really - I just think it's all about ARC / Modern memory management..
EDIT:
It should also work if you keep a reference on the button in your implementation..
#implementation myViewController
{
UIButton* myButton;
}
-(void)createButton
{
myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)];
[myButton setBackgroundColor:[UIColor blackColor]];
...
}
...
instead of
yourButton.titleLabel?.text = "T"
use this
yourButton.setTitle("TITLE", for: .normal)
Always do addSubview before setting the text on UIButton.

Localizing buttons in Xcode

This is my first question so far so I would love some understanding!
I am localizing entire application. I have no problem with labels that while pseudolocation translate properly. However, trying to achieve the same with buttons it doesn't work.
The code is
[self.Clear setTitle:NSLocalizedString(#"Clear",nil) forState:UIControlStateNormal];
and the .string file in en.plist content looks like this
"Clear" = "Blah";
The pseudolocation doesn't work and I would really appreciate some help. The simulator keeps showing Clear.
If you have any questions regarding this, I will answer!
Please don't eat me :P
In Interface Builder, you can set 4 strings, one for each of the states in the "State Config" dropdown.
OR, alternatively, in code, you set the button title for each state:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:NSLocalizedString(#"21.title", #"Norm!") forState:UIControlStateNormal];
[button setTitle:NSLocalizedString(#"21.title-highlighted", #"hi btn") forState:UIControlStateHighlighted];
[button setTitle:NSLocalizedString(#"21.title-selected", #"sel btn") forState:UIControlStateSelected];
[button setTitle:NSLocalizedString(#"21.title-disabled", #"dis btn") forState:UIControlStateDisabled];
Courtsey : Localize IOS button label

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

UIButton wierdness: Unable to set title for a custom button type

I'm trying to set the title for a custom button that I've created programmatically. The button's image and the frame come up fine, but the title doesn't. I can't really think of anything wrong with this code, so any help is apreciated!
self.helpButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.helpButton setFrame:CGRectMake(113.0, 685.5, 73.0, 40.0)];
UIImage *helpImg = [UIImage imageNamed:#"11_HelpCancel_Up.png"];
[self.helpButton setImage:helpImg
forState:UIControlStateNormal];
[self.helpButton setTitle:#"Help" forState:UIControlStateNormal];
[self.helpButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
// [self.helpButton setFont:[UIFont boldSystemFontOfSize:14.0]];
[self.view addSubview:self.helpButton];
Thanks,
Teja.
Use
[self.helpButton setBackgroundImage:helpImg forState:UIControlStateNormal];
- setImage:forState: seems to override - setTitle:forState:
Was having trouble with the button title showing up on my storyboard when I switched the type of button from system -> custom. The problem was the color of the text changed to white when I made the change so anyone having a similar issue, make sure to check the color of the button text.

Resources