Button image changing when pressed

Discussion in 'iOS Programming' started by mike1360, Oct 14, 2014.

  1. mike1360 macrumors newbie

    Nov 9, 2013
    Hi, Im pretty new to coding and was wondering how to, if possible, have a toggle button with the image changing as well. For example, the button displays an image of a happy face for easy mode. If someone was to click it, it turns to sad face for hard mode. But they can keep clicking back and forth and have it be able to register in the code so I could do something with that easy/hard mode? Thanks!
  2. pellets007 macrumors 6502a


    Jan 28, 2009
    New York
    If you only want two end states, just create an action that changes the value of a Boolean variable to true or false. The value is initially true, representing easy, and tapping the button sets it to false. From there you can changes the image depending on the value, and probably update the gameplay as well.
  3. iMacFarlane macrumors 65816


    Apr 5, 2012
    Adrift in a sea of possibilities
    Look up Apple's documentation for the UIButton reference. I'm sure there are some methods that allow you to alter a button's image based on its state (true/false), but I'm at work on a PC with outdated software on it, and the developer page gets rendered unreadable by this version of Internet Explorer, so I can't give you the method name right now.

    Or, if you're trying to conform to iOS 7 design paradigms, your button should look like this if true:

    : )

    or, if false:

    : (
  4. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    I believe UIControl's selected property should help you. UIButton is a subclass of UIControl.
  5. mike1360 thread starter macrumors newbie

    Nov 9, 2013
    Ok so what I need to do is have a boolean toggle from YES or NO when the button is clicked. Then from there, use the boolean data to tell the button image to change (such as if yes, display :) ...if no display :( ...)?
  6. PhoneyDeveloper macrumors 68040


    Sep 2, 2008

    That's not it.

    UIButton has the ability to be configured as a toggle button. @dejo is correct that UIControl has three relevant states, normal, highlighted, and selected. I believe that UIButton normally only uses normal and highlighted. However, you can still use setImage:forState: to set images for normal and selected.

    You need a little bit of code that toggles the state between normal and selected when the button is tapped. You don't set the image, you set the state. I'm pretty sure the button is only in the highlighted state transiently while it's being tapped.

    I did this in an app once but I can't remember which one or I'd show the code.

Share This Page