[iphone] UIButton: set image for selected-highlighted state

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 just grayed picture. Is it possible to set an image for highlighted state when the button selected?

my code:

[button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateHighlighted];
[button setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];

when I do:

[button setSelected:YES];

and press the button, the "pressed.png" image doesn't select.

This question is related to iphone cocoa-touch image uibutton selected ui-select2

The answer is


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

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);

In Swift 3.x, you can set highlighted image when button is selected in the following way:

// Normal state
button.setImage(UIImage(named: "normalImage"), for: .normal) 

// Highlighted state (before button is selected)
button.setImage(UIImage(named: "pressedImage"), for: .highlighted)

// Selected state
button.setImage(UIImage(named: "selectedImage"), for:  .selected)

// Highlighted state (after button is selected)
button.setImage(UIImage(named: "pressedAfterBeingSelectedImage"), 
                for:  UIControlState.selected.union(.highlighted))

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


In swift you can do:

button.setImage(UIImage(named: "selected"), 
                forState: UIControlState.selected.union(.highlighted))

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


I think most posters here miss the point completely. I had the same problem. The original question was about the Highlighted state of a Selected button (COMBINING BOTH STATES) which cannot be set in IB and falls back to Default state with some darkening going on. Only working solution as one post mentioned:

[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateSelected | UIControlStateHighlighted];

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.


Swift 3+

button.setImage(UIImage(named: "selected_image"), for: [.selected, .highlighted])

OR

button.setImage(UIImage(named: "selected_image"), for: UIControlState.selected.union(.highlighted))

It means that the button current in selected state, then you touch it, show the highlight state.


Swift 3

// Default state (previously `.Normal`)
button.setImage(UIImage(named: "image1"), for: [])

// Highlighted
button.setImage(UIImage(named: "image2"), for: .highlighted)

// Selected
button.setImage(UIImage(named: "image3"), for: .selected)

// Selected + Highlighted
button.setImage(UIImage(named: "image4"), for: [.selected, .highlighted])

To set the background image we can use setBackgroundImage(_:for:)

Swift 2.x

// Normal
button.setImage(UIImage(named: "image1"), forState: .Normal)

// Highlighted
button.setImage(UIImage(named: "image2"), forState: .Highlighted)

// Selected
button.setImage(UIImage(named: "image3"), forState: .Selected)

// Selected + Highlighted
button.setImage(UIImage(named: "image4"), forState: [.Selected, .Highlighted])

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];
}

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


Where you want to call from

[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];

The method:

-(void)test:(id)sender{
    UIButton *button=(UIButton *)sender;
    if (_togon){
      [button setTitleColor:UIColorFromRGB(89,89, 89) forState:UIControlStateNormal];
      _togon=NO;
    }
    else{
      [button setTitleColor:UIColorFromRGB(28, 154, 214) forState:UIControlStateNormal];
      _togon=YES;
    }
}

Credit above to Jorge but I improved it a bit giving the full working solution


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)

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to uibutton

How to make a simple rounded button in Storyboard? How to set the title text color of UIButton? How can I make a button have a rounded border in Swift? How to change UIButton image in Swift Changing text of UIButton programmatically swift Disable a Button How to change font of UIButton with Swift Attach parameter to button.addTarget action in Swift Change button background color using swift language Make a UIButton programmatically in Swift

Examples related to selected

UITableViewCell Selected Background Color on Multiple Selection How can I disable selected attribute from select2() dropdown Jquery? How to set a selected option of a dropdown list control using angular JS How to set the 'selected option' of a select dropdown list with jquery html select option SELECTED How to check if "Radiobutton" is checked? Programmatically select a row in JTable dropdownlist set selected value in MVC3 Razor UIButton: set image for selected-highlighted state jQuery remove selected option from this

Examples related to ui-select2

How to get Selected Text from select2 when using <input> How do I change selected value of select2 dropdown with JqGrid? Update select2 data without rebuilding the control set the width of select2 input (through Angular-ui directive) Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio? Can I apply the required attribute to <select> fields in HTML5? jQuery UI tabs. How to select a tab based on its id not based on index How To Get Selected Value From UIPickerView UIButton: set image for selected-highlighted state How can I pass selected row to commandLink inside dataTable or ui:repeat?