Reputation: 7570
I want a UIButton with image and title. I got the text appearing using -setTitleEdgeInsets
.
But I don't want to use trial and error to get the right position because the title of the button should be dynamic. I tried to determine the size and position of the UIButtons titleLabel object and set the titleEdgeInsets corresponding to it with the following code:
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(myButton.center.y - (myButton.titleLabel.bounds.size.height / 2),
- (myButton.center.x - (myButton.titleLabel.bounds.size.width / 2)),
myButton.center.y + (myButton.titleLabel.bounds.size.height / 2),
myButton.center.x + (myButton.titleLabel.bounds.size.width / 2))];
Am I missing or misusing something here?
Thanks in advance, with kind regards -Julian
Upvotes: 1
Views: 824
Reputation: 19321
Buttons can be a bit of a pain in how they manage their label and image subviews - it doesn't give you much control. This is because they update these values whenever the button state changes (or even more often) so if you have set the parameters manually your settings get lost. This is why you need to use methods like setTitleEdgeInsets:
- you are on the right track. :)
Things to watch out for:
myButton.center
is probably incorrect. That would be the center of your button in its parent view, you probably want to use half the button size here.titleLabel
.You could call layoutSubviews
on the button, and/or sizeToFit
on the label. However, you're really at the mercy of the opaque implementation details of UIButton
, so it might be best to calculate what you think the text/label size will be (using one of the sizeWithFont:*
methods in NSString
) and set a top and left edge inset to position the text.
Upvotes: 1