Reputation: 9566
I have an UIButton
with a titleLabel
and a backgroundImage
. I want to resize the button when it is in the highlighted state. This resize should affect the titleLabel
and the backgroundImage
, but I don't want to modify the hit area of the button.
Currently I am trying like this. It almost works, but it also affects the hit area:
- (void)setHighlighted:(BOOL)highlighted
{
if ( highlighted && !self.highlighted )
{
self.transform = CGAffineTransformMakeScale(scaleFactorOnTouch, scaleFactorOnTouch);
}
else if ( !highlighted && self.highlighted )
{
self.transform = CGAffineTransformMakeScale(1.0, 1.0);
}
[super setHighlighted:highlighted];
}
This causes that when you touch inside the button and drag outside its (extended by 100 pixels) hit area, there's this wiggle/tremor when you drag around the extended hit area edge. The wiggle is because the hitArea is changing constantly between the highlighted and non-highlighted state.
I also tried modifying the self.layer.transform property, but this also results in a change of the hit area.
If possible I would like to avoid setting a different backgroundImage for the highlighted state.
Upvotes: 0
Views: 349
Reputation: 534885
As you've rightly observed, overriding setHighlighted:
to change the transform of the button causes a kind of vicious loop. So don't do that! Instead, override backgroundRectForBounds:
, like this:
- (CGRect)backgroundRectForBounds:(CGRect)bounds {
CGRect result = [super backgroundRectForBounds:bounds];
if (self.highlighted)
result = CGRectInset(result, -3, -3);
return result;
}
That enlarges the drawn size of the button during highlighting, but the enlarged drawing is only visible because clipsToBounds
is NO. The bounds remain the same, and you can only touch within the bounds, so touch handling is unaffected.
That solves the background image part of the problem. If you really insist on changing the title size as well, I suppose you'll have to go on changing its transform. It would be less invasive to change the title's font (size) instead, though, I think - if that will work for your purposes.
Upvotes: 2