UIButton在突出显示时忽略contentMode(adjustsImageWhenHighlighted)

我使用[
myButton setImage:forState:];
为我的UIButton设置了一个
UIImage
我用
[[myButton imageView] setContentMode:UIViewContentModeScaleAspectFit];
把它设置为
contentMode
但是当你点击按钮时,它会回到
UIViewContentModeScaleToFill
并将我的图像拉出来。 使用
adjustsImageWhenHighlighted
修复此问题,但随后我松开了暗影效果,我想保留它。 有关如何应对此问题的任何建议?     
已邀请:
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];        
    }];
}
    
我对这个问题的解决方案(可能效率不高但它给你一个机会来定制高亮效果,我觉得它看起来比标准效果更好)是: 子类UIButton当然。 添加属性@property(非原子,保留)UIView * highlightView; 设置图像的方法(我的方法,你可以使用重要的不同模式来设置adjustsImageWhenHighlighted属性)
[self setImage:image forState:UIControlStateNormal];
[self setAdjustsImageWhenHighlighted:NO];
覆盖setHighlighted:方法如下:
- (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];
    }
}
这对我有用,但如果有更好的方法,我很乐意去了解它。     
出于某种原因,在为任何状态设置图像后设置内容模式时会发生这种情况。 确保在以编程方式设置图像之前以及在InterfaceBuilder上设置内容模式。要在IB上修复此问题,请确保删除为所有状态设置的所有图像,设置内容模式,然后重新放回图像。 这为我解决了这个问题。     

要回复问题请先登录注册