Search code examples
objective-cioscocoa-touchuibuttonsetbackground

UIButton to show BackgroundImage, Image and Title


I want to create a UIButton that uses its setBackgroundImage, setImage, and setTitle properties, but when I add setTitle in combination with setImage and setBackgroundImage the title doesn't appear.

I've tried the following.

[button setBackgroundImage:[UIImage imageNamed:@"image3.jpg"] forState:UIControlStateNormal]; 
[button setImage:[UIImage imageNamed:@"month_pct_general.png"] forState:UIControlStateNormal];
[button setTitle:[NSString stringWithFormat:@"%d",[button tag]] forState:UIControlStateNormal]; 
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
[button.titleLabel setFont:[UIFont boldSystemFontOfSize:20.0f]]; 
[button setTitleEdgeInsets:UIEdgeInsetsMake(45, 0, 0, 25)];

Solution

  • your title on button and on title your all image it there so add label on the image like this.

    UIButton *myButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    [myButton setFrame:CGRectMake(0,3,70,32)];
    [myButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [myButton addTarget:self action:@selector(compete) forControlEvents:UIControlEventTouchUpInside];
    UILabel *Label=[[UILabel alloc]initWithFrame:CGRectMake(6, 5, 60, 20)];
    [Label setText:@"label"];
    
    Label.backgroundColor=[UIColor clearColor];
    [Label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
    Label.textColor=[UIColor whiteColor];
    [myButton addSubview:Label];
    

    your all image above the title only so your title is in background so use label on image view.