Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set image and text on UIButton

I need to create button programatically with an image for normal and highlighted state as well text. I cannot build it using Interface Builder, because I need to create buttons over a UIScrollView. Here is the code I have so far:

- (void)loadView {
    CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame];
    scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect];
    scrollView.contentSize=CGSizeMake(320,960);

    UIImageView *tempImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.jpeg"]];

    UIImage * buttonImage = [UIImage imageNamed:@"contentlist_active.png"];

    self.view=scrollView;
    [scrollView addSubview:tempImageView2];

    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(22, 100, 277, 32);

    [btn setImage:buttonImage forState:UIControlStateNormal]; 

    [btn setTitle:@"hello world" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [scrollView addSubview:btn];

}

But the text on the button is not showing. If I comment out the setImage for button, then text shows perfectly, otherwise not. Can I have both text and an image at the same time?

like image 954
Haris Hussain Avatar asked Mar 27 '12 10:03

Haris Hussain


People also ask

How do I put the image on the right side of the text in a UIButton?

To make an UIButton's image align to the right side of the text, we force content flipping behavior to the one use it right-to-left language. 1 By adding this semanticContentAttribute = . forceRightToLeft , we force UIKit to mirrored our content which push our image to the right side of the text. Here is the result.

How do I use imageEdgeInsets?

The rule when it comes to titleEdgeInsets or imageEdgeInsets is to add equal and opposite offsets to the left and right insets. So if you add for example 8 points to the left title inset, you need to apply -8 points to the right inset.


3 Answers

UIButtons setImage sets the image above the title so you will not be able to see the text below it. So try to set image to your button with setBackgroundImage.

Objective-C:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

Swift:

myButton.setBackgroundImage(buttonImage, forState: .normal)
like image 105
ipraba Avatar answered Oct 20 '22 09:10

ipraba


You've made a mistake there, you're doing

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

instead of

[btn setImage:buttonImage forState:UIControlStateNormal]; 

This will work fine.

like image 25
Saroj Kumar ojha Avatar answered Oct 20 '22 09:10

Saroj Kumar ojha


Have you tried

[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted];

It might solve your problem.

like image 4
Rana Anees Avatar answered Oct 20 '22 08:10

Rana Anees