0

In the screenshot posted below, the cook, buyer and both are UIButton. User can click any one button. If one button is pressed, the button background color changes to green. After that when user clicks the register button, how do I check if the UIButton color is green or not. At least one UIButtonhas to be selected in order for the user to register.

enter image description here

I changed the button background color using this code:

@IBAction func cookact(_ sender: Any){

    cookbtn.backgroundColor = UIColor.green
}

How do I check if a button has been pressed?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
mouni
  • 327
  • 1
  • 3
  • 15
  • As you can take one var which will save `tag` of any button clicked and when register you can compare tag values – PiyushRathi Dec 19 '16 at 07:47
  • Hi piyushrathi, How can I compared the tag values.. can you explain the coding. – mouni Dec 19 '16 at 07:50
  • http://stackoverflow.com/questions/970475/how-to-compare-uicolors - check this – abhimuralidharan Dec 19 '16 at 07:52
  • You can directly compare the color values or you can use a 3 different bool values and use them as required. – abhimuralidharan Dec 19 '16 at 07:53
  • Check the situation of a button through the color I do not think it is the best option. You can use a tag as comments PiyushRathi or use another property even if it is not the button. The tag is a property that has the button and you access with boton.tag = Int depending on the tag value you are doing one thing or another – Spidvmp Dec 19 '16 at 07:54
  • @mouni is your issue resolved? – PiyushRathi Dec 19 '16 at 09:28
  • Yes it's resolved @ piyushRathi :) – mouni Dec 19 '16 at 14:25

2 Answers2

2

There are two ways to do it. One assigning the tag values to buttons and compare, Other easy solution is by declaring the enum values:

Declare the enum:

Swift:
    enum REGISTER_TYPE {
            case COOK
            case BUYER
            case BOTH
        }

Objective - C
    typedef enum {
    COOK = 1,
    BUYER = 2, 
    BOTH = 3
    }REGISTER_TYPE;

Now In your ViewController, create a property for the enum REGISTER_TYPE as

@property (nonatomic, assign) REGISTER_TYPE registerType;

When onClick the Button Action assign value to a property as

@IBAction func cookact(_ sender: Any){
   self.registerType = COOK
}



@IBAction func buyeract(_ sender: Any){
       self.registerType = BUYER
    }

So, self.registerType variable always holds a type of registration.

Hope it helps!

Imad Ali
  • 3,261
  • 1
  • 25
  • 33
1

You can use a bool value.When the user presses the cook button or buyer button,you can change this bool value to true and on the basis of this bool value you can determine wether the button was clicked or not.

Waqar Khalid
  • 119
  • 1
  • 12