Change colour of dark grey highlight when holding down custom UIButton?

前端 未结 5 1131
忘了有多久
忘了有多久 2021-02-02 07:56

I have a custom UIButton which is a cloud, transparent black and white .png file, with no down state, just one image. When tapping and holding the finger over it, i

相关标签:
5条回答
  • 2021-02-02 08:14

    Swift 3:

    myButton.adjustsImageWhenHighlighted = false
    
    0 讨论(0)
  • 2021-02-02 08:16

    If adjustsImageWhenHighlighted = NO is not working, set Button-Type to Custom (IB or programmatically).

    Default Button-Type: System, changes behavior of highlighted button.

    0 讨论(0)
  • 2021-02-02 08:18

    You can write a custom button that does it

    class ActionButton: UIButton {
    
      var originalBackgroundColor: UIColor!
    
      override var backgroundColor: UIColor? {
        didSet {
          if originalBackgroundColor == nil {
            originalBackgroundColor = backgroundColor
          }
        }
      }
    
      override var isHighlighted: Bool {
        didSet {
          guard let originalBackgroundColor = originalBackgroundColor else {
            return
          }
    
          backgroundColor = isHighlighted ? originalBackgroundColor.darken() : originalBackgroundColor
        }
      }
    
    0 讨论(0)
  • 2021-02-02 08:28

    You said you set a custom image for the UIControlStateHighlighted state. This should disable the default behaviour.

    If you still have problems you can disable this effect by setting the adjustsImageWhenHighlighted property to NO and use whatever custom effect you want.

    0 讨论(0)
  • 2021-02-02 08:28

    I was having a similar issue with a custom UIButton when the button was highlighting in grey every time it was pressed. I solved that problem by subclassing UIButton and in the implementation I overrode a single method, (void)setHighlighted: method and kept it empty:

    - (void)setHighlighted:(BOOL)highlighted
    {
       // Leave empty to prevent super from doing whatever
       // that it is doing to show the grey highlight.
    }
    

    That stopped any type of highlighting as I was not doing anything in the method. It's a better approach if all that you're trying to do is remove any highlighting effect.

    So in your code, create a subclass of UIButton, override the setHighlighted method, and then make your custom button a subclass of this custom class.

    0 讨论(0)
提交回复
热议问题