Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a custom UIButton resetting titleLabel to IB default on event firing

In IB I have a view with a UIButton of Type Custom, it has no image and the Title is set as "#placeholder"

The view is attached to a class that provides an IBOutlet and an IBAction for the button.

I set the button title with this: ViewClass.ButtonOutlet.titleLabel.text = @"%@",stringifiedVariable; whenever I need to.

This works ok. However, when I click the button, the titleLabel.text reverts back to "#placeholder".

I tried unchecking 'Highlighted Adjust Image' in the Drawing section (attributes tab) in the Inspector but the behaviour was still the same.

Can this change be prevented? or is there a better pattern that I should be using?

like image 303
Luke Mcneice Avatar asked Jul 09 '10 12:07

Luke Mcneice


People also ask

What is a Uibutton?

A control that executes your custom code in response to user interactions.

How do I change the text of a button in Swift?

You can omit UIControlState part and just write like button. setTitle("my text here", forState: . Normal) . I think it helps to mention: button is an IBOutlet (in contrast with the IBAction which contains this line of code) if you're leveraging Storyboard.

How do I center a button in Swift?

To create constraints select the button and click the Align icon in the auto layout menu. A popover menu will appear, check both “Horizontal in container” and “Vertically in container” options to center the button on the screen.


1 Answers

UIButton has a special method for setting the label.

  • (void)setTitle:(NSString *)title forState:(UIControlState)state

For instance

NSString *buttonText = [NSString stringWithFormat:@"%@",stringifiedVariable];
[ViewClass.ButtonOutlet setTitle:buttonText forState:UIControlStateNormal];

Check the documentation for more details.

like image 156
Pieter Jongsma Avatar answered Sep 22 '22 20:09

Pieter Jongsma