Starting a loop with a pushbutton and then looping until button is pressed again

I am creating a UI with an OLED, and I need the display to change when I push a button, and stay changed without my having to hold the button down. Currently, I am using a while loop as follows:

while (menuCount1 == 4 && clkenter == 0) {

I have my digital reads here for my buttons as well...

display.clearDisplay();
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(15,0);
display.println("Settings");
}

As soon as I let go of the button though, the loop stops (as it should), but what I need it to do is keep looping until I press the back button. So keep looping until an If command stops the loop. It works great if I don't read the buttons being pressed in the while loop, and just create an if --> break statement to get out of it, but I need to be able to read all of my buttons for the rest of the UI. Any ideas? Thanks so much everyone!

It can be like this:

#include <ezButton.h>

ezButton button(7);  // create ezButton object that attach to pin 7;

boolean displayed = false;

void setup() {
  button.setDebounceTime(50); // set debounce time to 50 milliseconds
  button.setCountMode(COUNT_FALLING);
}

void loop() {
  button.loop(); // MUST call the loop() function first

  if(button.isPressed()) {
    if(displayed == false) {
	  // DISPLAY CODE HERE
	} else {
	  // CLEAR CODE HERE
	}
	displayed = ~displayed;
  }
}

The above code used this button library

It's easy enough to do from first principles without resorting to a library, by following the technique of the state change detect tutorial, and toggle a boolean (as IoT_hobbyist did) each time there's a new press.

Side note: I think it's more common to use ! to mean not, rather then ~, so:

displayed = !displayed;

(In fact ~ didn't work when I tested it.....)

PS, since the nature of loop() is to loop, you probably could use if() rather than while() but without you posting a complete sketch it's difficult to give definitive advice.

twinkleyan:
It's easy enough to do from first principles without resorting to a library

Because the library supports "debounce", I think it is more convenient.

twinkleyan:
Side note: I think it's more common to use ! to mean not, rather then ~, so:

displayed = !displayed;

(In fact ~ didn't work when I tested it.....)

Great!, thank you

IoT_hobbyist:
Great!, thank you

Did you test the use of ~?

Although it didn't (seem to) work for me, it did actually compile; I have no idea what it actually did, if anything.

twinkleyan:
PS, since the nature of loop() is to loop, you probably could use if() rather than while() but without you posting a complete sketch it's difficult to give definitive advice.

I'm using a OLED, so when I tried "If", it just flickered the display, but the boolean "while" command worked great. I just used displayed = !displayed and that did the trick. Thanks all!!