Highlighting a UIControl subclass

大城市里の小女人 提交于 2019-12-01 02:59:54

I think UIControls automatically set their highlighted property correctly, based solely on touch events. What you need is to override -setHighlighted: method to implement a specific algorithm:

- (void) setHighlighted: (BOOL) highlighted {
    [super setHighlighted: highlighted];
    // Only as an example. Caution: looks like a disabled control
    self.alpha = highlighted ? 0.5f : 1.0f;
}
Loic Verrall

In the interests of keeping this answer up-to-date, here is the Swift version (of Costique's answer).

override var isHighlighted: Bool {
    didSet {
        alpha = self.isHighlighted ? 0.6 : 1.0 // Sets alpha to 0.6 if highlighted, or 1.0 if it's not.
    }
}

You may also like to fade the dimming of the UIControl. To do this, simply place the alpha assignment in an animation block, like this

override var isHighlighted: Bool {
    didSet {
        UIView.animate(withDuration: 0.25) {
            self.alpha = self.isHighlighted ? 0.6 : 1.0
        }
    }
}

To highlight subviews of UIControl properly you can use custom tint color. To enable this, somewhere in init methods or awakeFromNib you should change image rendering mode to always template:

self.imageView.image = [self.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
self.backgroundImageView.image = [self.backgroundImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
self.tintColor = [UIColor zst_blueColor]; // Use custom instead of system-defined color

So instead of changing alpha value we can change tint color and it will change its UIImageView subviews automatically. In the setHighlighted: method you can change text and tint color to a darker color:

- (void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];
    UIColor *tintColor = highlighted ? [UIColor zst_darkerBlueColor] : [UIColor zst_blueColor];
    self.tintColor = tintColor;
    self.titleLabel.textColor = tintColor;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!