I am trying to create a toggle button for each cell in my table. When pressed, it will change the image and when pressed again it will change the image again -- Toggle.
In the UIButton
class I don't see a selected
state.
I'm looking for a way to create a toggle button with UIButton so that I can change the state on each click.
This is how I'm doing it in rubymotion
right now using rmq
@fav_button.on(:touch) do |sender|
puts "pressed fav button for id: " + data[:id] + " and name: " + data[:name]
#how do I change the state here?
end
Since your question did mention rmq, here's an rmq way of doing it:
In
viewDidLoad
:Note that the toggle is achieved by querying the button's actual state. If you need to remember this for later use, you might want to save that in an instance variable.
In your stylesheet:
Note the use of
image_selected
. Well, this doesn't exist in rmq, but you can make that happen quite easily. If this is an rmq project, you'll have a stylers/ directory. In there, you should see ui_button_styler.rb. Here's the code to make the highlighted state a first-class citizen:As you can see, your controller code remains clean, the initial settings of the button are shifted to the stylesheet and you have neatly extended rmq to understand the selected state.
You can do it in a very easy approach. First of all, in your
viewDidLoad
set tag for your button. Let's sayself.toggleButton.tag = 111
. Now in your button action function, you can toggle the button like :You can change the image of the button like this
[self.toggleButton setImage://some image forState:UIControlStateNormal];
.It's the easiest way I think. Hope it will help.Swift 4.0 Solution (using Storyboards)
First, ensure the
UIButton
Type is set toCustom
in the Attributes Inspector.Below screenshot demonstrates reference to
toggleButton
in Storyboard, andTouch Up Inside
Event, ie: a user tapping the button, which fires offdidPressButton
below.My easiest logic to toggle button image. :)
You can create toggle button easily, you just need to set respective images for respective states, after that, you can use the
selected
property to toggle between these images.I made a pure objective-c code to show how you can do that, but you can set the images anyway in Storyboards ou Xibs too, check out:
I hope this can help you.