1

I'm trying to get the image (which is build in IB) on the right side of the text. An idea I found here was to subclass the UIButton and override:

- (CGRect)imageRectForContentRect:(CGRect)contentRect

and

- (CGRect)titleRectForContentRect:(CGRect)contentRect` which I did.

But in that example the image is pushed all the way to the right edge of the button. I want it to appear just after my centred text. So, I thought, I could do this if I could get the width of the label with a certain font.

Which works perfectly. But. If I do that in the imageRectForContentRect like this:

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGSize textSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: self.titleLabel.font}];
}

I get an infinite loop (since calling the self.titleLabel calls imageRectForContent, which calls textSize code and so forth.

So that would not work.

Is there another way to easily could get my image on the right side of the text with a button with centred text?

I was trying this approach since I want to support multiple languages and the text of the button could have different lengths.

Community
  • 1
  • 1
Matthijn
  • 3,126
  • 9
  • 46
  • 69

2 Answers2

11
- (void)swapImageText
{
    self.transform = CGAffineTransformScale(self.transform, -1.0f, 1.0f);
    self.titleLabel.transform = CGAffineTransformScale(self.titleLabel.transform, -1.0f, 1.0f);
    self.imageView.transform = CGAffineTransformScale(self.imageView.transform, -1.0f, 1.0f);
}

My category for UIButton. All other code will be violated, if it assumes any UIButton has identity transform.

user2616346
  • 465
  • 1
  • 5
  • 12
3

A simple way of acheive this,

In IB, Within Attribute Ispector, last options is "Edge" Select Image from dropdown of Edge and increase its left value, Now select title and increase its left value in negative.

It will give you your desired result.

Surjeet Singh
  • 11,691
  • 2
  • 37
  • 54
  • 2
    Yes, but that would only work for a string of exact that length. And in an translation the length could be different. – Matthijn Jul 12 '14 at 19:16
  • Can you increase your button length according to the different-different length of st string. If yes, then after set Text on button, you have to change inset of image by self.imageEdgeInsets = UIEdgeInsetsMake (0.0, 0.0 , (btSize.width - imageSize.width), 0.0); – Surjeet Singh Jul 13 '14 at 07:00