I set a UIImage
for my UIButton using [myButton setImage:forState:];
and I set it's contentMode
using [[myButton imageView] setContentMode:UIViewContentModeScaleAspectFit];
But when you tap the button, it goes back to UIViewContentModeScaleToFill
and stretches my image out.
using adjustsImageWhenHighlighted
fixes this, but then I loose the darkening effect, which I would like to keep.
Any suggestions on how to cope with this?
UIButton *imageBtn = [UIButton ...
imageBtn.adjustsImageWhenHighlighted = NO;
[imageBtn addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];
[imageBtn addTarget:self action:@selector(doHighlighted:) forControlEvents:UIControlEventTouchDown];
[imageBtn addTarget:self action:@selector(doHighlighted:) forControlEvents:UIControlEventTouchDragEnter];
[imageBtn addTarget:self action:@selector(doCancelHighlighted:) forControlEvents:UIControlEventTouchDragExit];
-(void)doSomething:(UIButton *)button{
...
[self performSelector:@selector(doCancelHighlighted:) withObject:button afterDelay:0.2f];
}
-(void)doHighlighted:(UIButton *)button{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 300, 300)];
imageView.backgroundColor = [UIColor blackColor];
imageView.alpha = 0.7;
imageView.tag = 1000;
[button addSubview:imageView];
}
-(void)doCancelHighlighted:(UIButton *)button{
UIView *view = [button subviewWithTag:1000];
[UIView animateWithDuration:0.2f animations:^{
view.alpha = 0;
} completion:^(BOOL finished) {
[view removeFromSuperview];
}];
}
my solution to this problem (maybe not efficient but it gives you an oportunity to customize the highlight effect, i think it looks better then standard one) is:
method for setting image (my method, you can use different mode important to set adjustsImageWhenHighlighted property)
[self setImage:image forState:UIControlStateNormal];
[self setAdjustsImageWhenHighlighted:NO];
override setHighlighted: method like so:
\- (void)setHighlighted:(BOOL)highlighted {
if (!highlightView) {
self.highlightView = [[[UIView alloc] initWithFrame:self.bounds] autorelease];
self.highlightView.backgroundColor = [UIColor darkGrayColor];
self.highlightView.alpha = 0.0;
[self addSubview:self.highlightView];
}
if (highlighted) {
[UIView beginAnimations:@"highlight" context:nil];
[UIView setAnimationDuration:0.2];
highlightView.alpha = 0.5;
[UIView commitAnimations];
}
else {
[UIView beginAnimations:@"highlight" context:nil];
[UIView setAnimationDuration:0.2];
highlightView.alpha = 0.0;
[UIView commitAnimations];
}
}
This works for me, but if there is a better way, i'll be glad to get to know it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With