UIButton: set image for selected-highlighted state

后端 未结 15 2748
花落未央
花落未央 2020-11-28 19:23

I set an images for button\'s states Normal,Highlighted and Selected, but when the button in selected state and I press/highlight it I didn\'t see my highlighted image but j

相关标签:
15条回答
  • 2020-11-28 19:44

    I had problem setting imageView.highlighted = NO; (setting YES worked properly and the image changed to the highlighted one).

    The solution was calling [imageView setHighlighted:NO];

    Everything worked properly.

    0 讨论(0)
  • 2020-11-28 19:49

    If you need the highlighted tint which the OS provides by default when you tap and hold on a custom button for the selected state as well, use this UIButton subclass. Written in Swift 5:

    import Foundation
    import UIKit
    class HighlightOnSelectCustomButton: UIButton {
        override var isHighlighted: Bool {
            didSet {
                if (self.isSelected != isHighlighted) {
                    self.isHighlighted = self.isSelected
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 19:50

    If you have a good reason to do that, this will do the trick

    add these targets:

    [button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    
    
    -(void)buttonTouchDown:(id)sender{
        UIButton *button=(UIButton *)sender;
        if(button.selected){
            [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
        }
    }
    
    -(void)buttonTouchUp:(id)sender{
        UIButton *button=(UIButton *)sender;
        [button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
    }
    
    0 讨论(0)
提交回复
热议问题