UIButton: set image for selected-highlighted state

后端 未结 15 2746
花落未央
花落未央 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:25

    I found the solution: need to add addition line

    [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
    
    0 讨论(0)
  • 2020-11-28 19:29

    In my case, I have to change the UIButton.Type from .custom to .system

    And:

    button.setImage(UIImage(named: "unchecked"), for: .normal)
    button.setImage(UIImage(named: "checked"), for: [.selected, .highlighted])
    

    When handling tapping:

    button.isSelected = !button.isSelected

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

    You can do this in Interface Builder.

    Select the UIButton you wish to set in IB then go to the attributes inspector.

    In the screen shots,I am using a custom button type , but that does not matter.

    Custom Default

    enter image description here

    enter image description here

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

    If someone's wondering how this works in Swift, here's my solution:

    button.setImage("normal.png", forState: .Normal)
    button.setImage("highlighted.png", forState: .Highlighted)
    button.setImage("selected.png", forState: .Selected)
    
    var selectedHighLightedStates: UIControlState = UIControlState.Highlighted
    selectedHighLightedStates = selectedHighLightedStates.union(UIControlState.Selected)
    button.setImage("selectedHighlighted.png", forState: selectedHighLightedStates)
    
    0 讨论(0)
  • 2020-11-28 19:35

    Xamarin C#

    Doing bitwise OR doesn't work for some reason

    button.SetImage(new UIImage("ImageNormal"), UIControlState.Normal);
    button.SetImage(new UIImage("ImagePressed"), UIControlState.Selected | UIControlState.Highlighted | UIControlState.Focused);
    

    The following works

    button.SetImage(new UIImage("ImageNormal"), UIControlState.Normal);
    button.SetImage(new UIImage("ImagePressed"), UIControlState.Selected);
    button.SetImage(new UIImage("ImagePressed"), UIControlState.Highlighted);
    button.SetImage(new UIImage("ImagePressed"), UIControlState.Focused);
    
    0 讨论(0)
  • 2020-11-28 19:37

    Correct me if I am wrong. By doing

       [button setSelected:YES];
    

    you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png

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