I have seen a bunch of similar questions, but noone got the answer I am looking for. When I use this code to make a UIButton and set it's titleLabel, the UIButton appear, but the titleLabel won't appear.
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[button setBackgroundImage:[UIImage imageNamed:#"button.png"] forState:UIControlStateNormal];
button.titleLabel.text = #"Title";
button.titleLabel.font = [UIFont fontWithName:#"System-Bold" size:25.0f];
[self.view addSubview:button];
This code displays the button, but not the titleView, it's title. Why can that be? I am developing for iOS 6 and higher.
NOTE 1: I am not looking for an option like this:
[button setTitle:#"Title" forState:UIControlStateNormal];
Because I have to use the titleLabel to set it's font and fontSize.
NOTE 2: I can't create a UILabel and add it as a subView of the button. Since the button is later animating.
You always need to specify ControlState when updating button's title!
There are four possible values for UIButtons:
UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
so for example:
[button setTitle:#"Title" forState:UIControlStateNormal];
and then you can set custom settings for titleLabel:
[button.titleLabel setFont:[UIFont fontWithName:#"Zapfino" size:20.0]];
[button.titleLabel setTextColor:[UIColor blueColor]];
[button setTitle:#"Title" forState:UIControlStateNormal];
Is the correct way to set the title string.
titleLabel is used to set the font and color.
Try using...
[button setNeedsLayout];
[button layoutIfNeeded];
It will force button to update the layout.
If in the storyboard with a custom button image from assets like me
Check-in Attribute inspector
Check-in Attribute inspector set asset image as a background
Although this property is read-only, its own properties are read/write. Use these properties primarily to configure the text of the button. For example:
UIButton *button = [UIButton buttonWithType: UIButtonTypeSystem];
button.titleLabel.font = [UIFont systemFontOfSize: 12];
button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
Do not use the label object to set the text color or the shadow color. Instead, use the setTitleColor(:for:) and setTitleShadowColor(:for:) methods of this class to make those changes. To set the actual text of the label, use setTitle(_:for:) (button.titleLabel.text does not let you set the text).
The titleLabel property returns a value even if the button has not been displayed yet. The value of the property is nil for system buttons.
in swift :
button.setTitle("your text", for: .normal)
button.setTitleColor(.white, for: .normal)
TLDR - try this saveButton.titleLabel?.layer.zPosition = 10
This was a frustrating one for me. I created a UIButton programmatically, added constraints, and added a gradient background (this is what caused my problem...I think). Then I needed to update the font:
saveButton.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
saveButton.setTitle("Save", for: .normal)
Notice I'm setting the title in the correct way. But still, no title showing. The craziest part - when I clicked "Debug View Hierarchy" I could see the title right there! If I didn't change the font, the title showed as well. Confusing. Then I added this (literally flinging spaghetti and seeing what stuck):
saveButton.titleLabel?.layer.zPosition = 10
It worked. It seems like some combination of gradient background, setting the font, etc was putting the button's internal title label at the bottom of its layers.
Related
I have created a custom UIButton for an iOS 4.3+ application. I wanted to make the background image stretch, so I and used the following methods to set its background image:
[myButton setBackgroundImage:[[UIImage imageNamed:myImagePath] stretchableImageWithLeftCapWidth:leftStretchValue topCapHeight:topStretchValue] forState:UIControlStateNormal]
[myButton setBackgroundImage:[[UIImage imageNamed:myHighlightedImagePath] stretchableImageWithLeftCapWidth:eftStretchValue topCapHeight:topStretchValue] forState:UIControlStateHighlighted]
[myButton setBackgroundImage:[[UIImage imageNamed:mySelectedImagePath]
stretchableImageWithLeftCapWidth:eftStretchValue topCapHeight:topStretchValue] forState:UIControlStateSelected]
I have added an event handler to the custom button
[myButton addTarget:self action:#selector(buttonHighlighted:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:#selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
In the above mentioned methods, I have set the selected and the highlighted state of the button accordingly. I have changed the frame of the UIButton to adjust the dimensions of an irregular image (mySelectedImage and myHighlightedImage, neither of which is a rectangle), so that it gets aligned properly along with myImage.
- (void) buttonSelected {
myButton.selected = !myButton.selected; //setting the selected property to NO in the viewDidLoad
//code to change the frame of the UIButton to accomodate the irregular image
}
- (void) buttonHighlighted {
myButton.highlighted = YES;
}
The problem I am facing is that when I select myButton, a gray color overlay is displayed on myImage for a very short time before the images myHighlightedImage and mySelectedImage are displayed as its background. I have set the background color of myButton as clearColor, thinking that might be the reason, but it is not getting solved.
What could be the possible issue... ?
button.adjustsImageWhenHighlighted = NO;
I think that is what you are looking for..
I initiated my button like this:
meetingPointButton = [UIButton buttonWithType:UIButtonTypeCustom];
[meetingPointButton setTitle:#"Alpha" forState:UIControlStateNormal];
[meetingPointButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
Afterwards I change its title and when doing so also want to alter the title color. I am using following code:
[meetingPointButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[meetingPointButton setTitle:#"Beta" forState:UIControlStateNormal];
The title changes to "Beta" but its color stays light gray. Any ideas how to solve that issue?
As prince said use:
meetingPointButton.titleLabel.textColor = [UIColor blackColor];
Leaving out forState:UIControlStateNormal makes the button switch right away instead of the next time it recieves to go to UIControlStateNormal. Knowing this you could also just set the button to UIControlStateNormal after your original code.
Try this:
meetingPointButton.titleLabel.textColor = [UIColor blackColor];
to change text color.
For people that might be coming to this question on the basis of the title, one reason you might not see an effect when you change the color of the title is because the UIButton's string might be an NSAttributedString. UIButton has special methods to set an attributed string for the title and when a title is set that way setting the title text color has no effect. You need to change the attributed title NSAttributedString instead.
A button can be added by:
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(100, 100, 160, 50);
[myButton setTitle:#"click me" forState:UIControlStateNormal];
[self.view addSubview:myButton];
but can we go with the initWithFrame method:
UIButton *myButton2 = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 160, 50)];
//myButton2.buttonType = UIButtonTypeRoundedRect;
myButton2.titleLabel.text = #"click me";
[self.view addSubview:myButton2];
but line 2 above is commented out because it causes an error for a "read only" property, and with that line commented out, still no button shows up at all... can a UIButton be added if using initWithFrame to begin with?
(update: I set a yellow background to see the view's area, and found that the label text of button 2 actually shows up as "click me" in white... but touching it has no visual effect... so I wonder how to change code sample 2 to make it work...)
Yes of course it can. I got into a little bit of a discussion as to that readonly buttonType property a while back. The general concensus is that there is neither a safe way, nor a good reason, for anyone to switch the type of a button. And besides, +buttonWithType returns an instance of UIButton just as well as +Alloc and -init do, so it isn't a problem.
I'm trying to add subviews to a UIButton. This is working fine right now. But the button isn't clickable anymore as soon as I add the subviews.
I use the following code:
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*100+24, row*80+10, 64, 64);
[button addSubview:asyncImage];
[button addSubview:price];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
The button works again if I remove the 2 addSubview: methods. If anyone knows how to fix this it would be great!
I found a quick solutions. I needed to set the asyncImageView to the following:
asyncImage.userInteractionEnabled = NO;
asyncImage.exclusiveTouch = NO;
After this, it worked!
try:
[UIButton buttonWithType:UIButtonTypeCustom];
instead of:
[UIButton buttonWithType:UIButtonControlType];
The important thing here is to make sure that userInteractionEnabled will be set to NO. Fortunately it works immediately for UIImageView and UILabel (maybe for other subclasses of a UIView but those are the most popular subviews added to button) because by default for this classes it is set to NO by default. Unfortunately it is set to YES in UIView so make sure to change it in that case. Messing around with any other flags shouldn't be necessary. The nature of problem is that many people do not know that default value of this flag is different in subclasses.
Have you tried to put:
[asyncImage setUserInteractionEnabled:YES];
in the same sitiation i make this action:
inherit from UIButton and add all labels and imageview's of button to self, finally put new button to view as last subview and add targets of self button to this last button(also set backgroundColor to clearColor for transparent). now it will be clickable and works fine.
In Swift, test that is you have your UIButton blocked
uibtn.userInteractionEnabled = false
uibtn.exclusiveTouch = false
I added a label to the subview button.
For a very long time I was looking for why my text in the button is not clickable. Solution in this thread:
myLable.isUserInteractionEnabled = false
I want to make a UIButton with type UIButtonTypeCustom (for the shape). I want to assign the title using button.titleLabel because I need to specify the font. The following code looks like it should work, but doesn't -- no label shows up, period.
UIImage *editButtonImage = [UIImage imageNamed: #"editButton.png"];
float width = editButtonImage.size.width;
float height = editButtonImage.size.height;
UIButton *editButton = [UIButton buttonWithType: UIButtonTypeCustom];
editButton.frame = CGRectMake(0, 0, width, height);
[editButton setBackgroundImage: editButtonImage forState: UIControlStateNormal];
editButton.adjustsImageWhenHighlighted = YES;
editButton.titleLabel.text = #"Edit";
editButton.titleLabel.textColor = [UIColor whiteColor];
editButton.titleLabel.textAlignment = UITextAlignmentCenter;
editButton.titleLabel.font = [UIFont fontWithName: #"Helvetica" size: 14];
[self.view addSubview: editButton];
Everyone always says to use setTitle:forState: but that gives you a font I don't like. The titleLabel method is NOT deprecated -- it should work.
I have run into this several times before and always just worked around it, but I'd really like to figure it out. Any ideas?
Setting the titleLabel's text property like that has no effect. Instead, call -setTitle:forState: on the button:
[editButton setTitle:#"Edit" forState:UIControlStateNormal]
The reason for this is because the button can have different titles for different states (e.g., UIControlStateDisabled, UIControlStateHighlighted). Setting a property for the UIControlStateNormal control state will apply to all the states if you don't specify the others explicitly.
Per the documentation for UIButton:
This class provides methods for setting the title, image, and other appearance properties of a button. By using these accessors, you can specify a different appearance for each button state.
You can customize label's color and shadow color based on the state. See -setTitleColor:forState and -setTitleShadowColor:forState, respectively. The rest of the properties on titleLabel, such as textAlignment and font, should work as you have them set now and should apply to all the control states.
Specifically, see the documentation for UIButton's titleLabel property: https://developer.apple.com/documentation/uikit/uibutton/1623992-titlelabel
titleLabel itself is read-only, but that doesn't mean you can't change the values of its own properties, such as font, line break mode, etc.
Here's how I worked it out using Swift 4.2.
counterButton.setTitle("Start Counter",
for:UIControl.State.normal)