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
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))
In swift you can do:
button.setImage(UIImage(named: "selected"),
forState: UIControlState.selected.union(.highlighted))
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];
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])
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
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.