Reputation: 3234
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.
Upvotes: 1
Views: 5000
Reputation: 11949
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.
Upvotes: 3
Reputation: 483
- (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.
Upvotes: 11