简体   繁体   中英

Image Checkbox in Objective-C

I'm working on a form for the iphone and I would like a female/male button choice. The buttons originally have an M and an F written on them and when you choose one, an image flips over. I managed to display the images when the buttons are pressed. The problem I was having is that they were able to both be displayed at the same time but when one is enabled the other image should disappear. I've tried to correct it and now the program crashes. implementation file:

-(IBAction) setCheckBox2: (id) sender
{
    UIImage *selected = [UIImage imageNamed:@"female.tiff"];
    // UIImage *notSelected = [UIImage imageNamed:@"male.tiff"];

    if (sender == selected)

    {
        [sender setImage:selected];
    }
    else
    {

        [sender setImage:NO];  
    }

Then I was going to create another function for the male image being selected. Any suggestions?

Thanks!

You are testing that sender == selected hence implying that sender is of type UIImage , and then sending setImage: to sender ... with itself as parameter.

This doen't make sense. I think what you were trying to do must look something like:

-(IBAction) setCheckBox2: (UIImageView *) sender
{
    UIImage *selected = [UIImage imageNamed:@"female.tiff"];
    UIImage *notSelected = [UIImage imageNamed:@"male.tiff"];

    if (sender.image == selected)

    {
        [sender setImage:notSelected];
    }
    else
    {

        [sender setImage:selected];  
    }
}

Why not you are using default (for not selected) and selected (for selected) property for these two state. The advantage to do this is you will not have to write a bunch of code. OK set selected image and default image.

Take a global variable of UIButton for currentSelectedButton . connect both the UIButton with single IBActionMethod named genderButtonClicked (or you want). Now

-(IBAction)genderButtonClicked:(UIButton)sender
{
    if(currentSelectedButton)
        [currentSelectedButton setSelected:FALSE];
    currentSelectedButton = sender;
    [currentSelectedButton setSelected:TRUE];
}

I Think this will solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM