In the project, we often encounter such a problem: Because the network is slow, the user will be impatient to click the button, so that the result: the relevant code is repeated over and over again, if the button event is a network request, which in turn leads to a network request loop. So the way we solve this is to add a button to prevent repeated clicks when clicking on an event.
Specifically, there are several ways to do this:
1. Using the Performselector method
-(void) Performselector: (SEL) aselector withobject: (nullable ID) anargument Afterdelay: (nstimeinterval) delay;
We add a deferred execution event to the Click event, during which the button's enabled setting is no, which cannot be clicked. After the delay time is set to Yes. Prevent users from repeating the Click button in this way.
The code is as follows:
-(void) buttonclicked: (ID) sender
{
sender.enabled = NO;
// prevent users from repeating clicks
[self performselector:@selector(changebuttonstatus:) withobject:nil afterdelay:1.0f];
}
-(void) Changebuttonstatus: (ID) sender
{
sender.enabled = YES;
}
The above method can be a good solution to our repeated click button problem, but the more recommended is the following method:
2, the use of Cancelpreviousperformrequestswithtarget and performselector combination method (Recommended Use)
+ (void) Cancelpreviousperformrequestswithtarget: (ID) atarget selector: (SEL) aselector Object: (nullable ID) anargument;
-(void) Performselector: (SEL) aselector withobject: (nullable ID) anargument Afterdelay: (nstimeinterval) delay;
The principle is: each time we click on the button, the first execution of the Cancel button click on the execution of the event, and then to execute a deferred execution method (the method executes the button execution of the event). The code is as follows:
-(void) buttonclicked: (ID) sender
{
// do a button here to do the things you want to do.
}
-(void) starbuttonclicked: (ID) sender
{
//The task is canceled before the time of execution.
[Self- class] cancelpreviousperformrequestswithtarget:self Selector :@selector(buttonclicked:)object: sender];
[self performselector:@selector(buttonclicked:)withobject: Sender Afterdelay :0.2f];
}
The second is our recommended method, but both of these methods can solve the problem of the button being repeatedly clicked.
iOS prevents users from repeatedly tapping the button (buttons) issue