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

Ken*_*ker 12 scaling image uibutton contentmode ios

UIImage为我的UIButton 设置了一个[ myButton setImage:forState:]; 和我设置它contentMode使用[[myButton imageView] setContentMode:UIViewContentModeScaleAspectFit]; 但是当你点击按钮时,它会回到UIViewContentModeScaleToFill并拉伸我的图像.

使用adjustsImageWhenHighlighted修复这个,但后来我松了变暗效果,我想保留.

有关如何应对此问题的任何建议?

小智 2

我对这个问题的解决方案(可能效率不高,但它给了你一个定制高亮效果的机会,我认为它看起来比标准的更好)是:

  • 当然是 UIButton 的子类。
  • 添加属性@property(非原子,保留)UIView *highlightView;
  • 设置图像的方法(我的方法,您可以使用不同的模式重要来设置 adjustmentImageWhenHighlighted 属性)

    [self setImage:image forState:UIControlStateNormal];
    [self setAdjustsImageWhenHighlighted:NO];
    
    Run Code Online (Sandbox Code Playgroud)
  • 重写 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];
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

这对我有用,但如果有更好的方法,我会很高兴了解它。