Button image changing when pressed

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

  1. mike1360 macrumors newbie

    Joined:
    Nov 9, 2013
    #1
    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

    pellets007

    Joined:
    Jan 28, 2009
    Location:
    New York
    #2
    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

    iMacFarlane

    Joined:
    Apr 5, 2012
    Location:
    Adrift in a sea of possibilities
    #3
    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

    dejo

    Staff Member

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

    Joined:
    Nov 9, 2013
    #5
    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 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #6
    @mike360,

    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