0

I want to set image and title for aUIButton. Here both are visible when I am using the background image for the button. But when I am using setImage Method then title is no longer visible.

[self setBackgroundColor:[UIColor clearColor]];
    [self setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 80.0, 0.0, 0.0)];
    [self setTitle:@"Kansal Ji" forState:UIControlStateNormal];
    [self setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.titleLabel setBackgroundColor:[UIColor blueColor]];

    [self setImage:[UIImage imageNamed:@"categories.png"] forState:UIControlStateNormal];
    [self.imageView setBackgroundColor:[UIColor greenColor]];
    [self setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0,kWidthOfView(self)-kHeightOfView(self))];
    self.clipsToBounds = YES;

Please help regarding this.Here following code is done in the subclass of UIButton.

clearlight
  • 12,255
  • 11
  • 57
  • 75
Rahish Kansal
  • 39
  • 1
  • 8
  • 1
    By default Button's have text. If you want to use an foreground image with the button you lose the text option. You'll have to add a separate view such as a UILabel to it as the title. You can position that over the button or near it or however you see fit and use constraints with Auto Layout (ideally) to position it the way you'd like. The background image makes sense. Foreground image is in the foreground, and so is the title, so where would the label go by default? That would be an assumption and a choice that only the designer would really have the perspective on. – clearlight Mar 28 '15 at 14:30
  • We can set both image and title to the button. But it can be done using setBackgroundImage method. Here when I am using setImage method then it hides the title. – Rahish Kansal Mar 28 '15 at 14:34
  • I updated my answer to acknowledge the background image. Since images are different, if you wanted to add a title to it, where should the UIButton *assume* you want that title to align with the image? It really can't. Plus it's a foreground image, and the title is also in the foreground. It looks like you can achieve what you want but if you want the button to be an image button you have to handle the title separately. – clearlight Mar 28 '15 at 14:36
  • 1
    http://stackoverflow.com/questions/2507248/uibutton-of-type-uibuttontypecustom-will-not-display-title-iphone – oren Mar 28 '15 at 14:48
  • ok..so no other option than using separate label? and thanks for supporting. – Rahish Kansal Mar 28 '15 at 16:03

0 Answers0