【问题标题】:Highlighting a UIControl subclass突出显示 UIControl 子类
【发布时间】:2011-05-24 15:03:57
【问题描述】:


基本上我需要一个图像按钮,特别是一个自定义对象:
1) 点击时调用控制器的动作
2) 封装自定义数据
3) 由包装视图自动移动(不相关)

好吧,我通过 UIControl 的子类得到了所有这些(因为不推荐子类化 UIButton 并且子类化 UIImageView 很难管理第 1 点)。 但是现在突出显示它的正确方法是什么? 我想在以任何方式点击时突出显示控件(即使是简单的 alpha 瞬间减少)。

对于beginTrackingWithTouchendTrackingWithTouch,我无法识别唯一的UIControlEventTouchUpInside 事件。

控制器中的视图动画?在我看来这是一个粗略的解决方案

有没有简单直接的解决方案?

谢谢:(

【问题讨论】:

    标签: iphone uiimageview uibutton highlighting uicontrol


    【解决方案1】:

    我认为 UIControls 仅根据触摸事件自动正确设置其突出显示的属性。你需要重写-setHighlighted: 方法来实现特定的算法:

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

    【讨论】:

    • 如果有子视图,别忘了设置mySubview.userInteractionEnabled = NO(否则不会注册tap,也不会触发高亮)。
    【解决方案2】:

    为了让这个答案保持最新,这里是 Swift 版本(Costique 的答案)。

    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.
        }
    }
    

    您可能还想淡化 UIControl 的变暗。为此,只需将 alpha 分配放在一个动画块中,如下所示

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

    【讨论】:

    • 我发现使用didSet会导致触摸延迟。 set(highlighted) { 工作得更好 - 但前提是我不打电话给 super
    【解决方案3】:

    要正确突出UIControl 的子视图,您可以使用自定义色调颜色。要启用此功能,请在 init 方法或 awakeFromNib 的某处将图像渲染模式更改为 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
    

    因此,我们可以更改色调颜色,而不是更改alpha 值,它会自动更改其UIImageView 子视图。在setHighlighted: 方法中,您可以将文本和色调更改为更深的颜色:

    - (void)setHighlighted:(BOOL)highlighted
    {
        [super setHighlighted:highlighted];
        UIColor *tintColor = highlighted ? [UIColor zst_darkerBlueColor] : [UIColor zst_blueColor];
        self.tintColor = tintColor;
        self.titleLabel.textColor = tintColor;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多