简体   繁体   中英

How to detect a button click - logic error code provided

What I want to do is, when I click the button once it should get highlighted (I am loading an image to show the highlighted effect), and when I click the button again (for the second time) it should remove the highlighted image and add a normal image. It should also add and remove elements from a Mutable Array.

But what is happening is that, when I click (once or several times) it only adds images, and does not remove any. Help me please

Code
I am adding a button. The below 2 lines are placed in the viewdidload method

UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // then i set the size etc, and do the following

        [but addTarget:self action:@selector(butclick:) forControlEvents:UIControlEventTouchUpInside];

    -(void)butclick:(id)sender{

        if([sender isSelected]==NO) {
            [sender setBackgroundImage:[UIImage imageNamed:@"highlighted.png"] forState:UIControlStateNormal];
            [sender setSelected:YES];

            [self.mutArry addObject:[sender titleForState:UIControlStateSelected]];

        } else {
            [sender setBackgroundImage:[UIImage imageNamed:@"nothighlighter.png"] forState:UIControlStateNormal];
            [sender setSelected:NO];
            [self.mutArry removeObject:[sender titleForState:UIControlStateSelected]];

        }

}

u might want to use a BOOL (like a flag) to use it instead of using the highlight idea.

toggle it with each press, and according to its value perform ur operation, it will always add a value once and remove a value the next press. the first is according to what the initial value of that flag is.

    if (flag)
    {
    //add your object and set to highlight
       flag = NO;
    }else
    {
       flag = yes;
       //remove object and set to not highlighted
    }

set the flag to NO when when it was found true, and to YES when it was found false. ensures it will keep changing

Have the following property defined and synthesized in that class

BOOL selected;

in viewDidLoad, set is to false

self.selected = NO;

Now do the following:

-(void)butclick:(id)sender{

    if(!self.selected) {
        [sender setBackgroundImage:[UIImage imageNamed:@"highlighted.png"] forState:UIControlStateNormal];
        self.selected =  YES;

        [self.mutArry addObject:[sender titleForState:UIControlStateSelected]];

    } else {
        [sender setBackgroundImage:[UIImage imageNamed:@"nothighlighter.png"] forState:UIControlStateNormal];
        self.selected = NO;
        [self.mutArry removeObject:[sender titleForState:UIControlStateSelected]];

    }

}

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