简体   繁体   中英

How to dynamically change UIButton title during Touch and Hold

I am following this answer to change title of my UIButton. To sum up, here is what I have to do:

  1. When user touches down, title of the button starts changing.

  2. While touch is held, it should change every 1 second, and user should be able to see it.

  3. When user touches up (stops touching), button title should be fixed to the last value held.

I handle 1 using setTitle:forState:

I handle 2 using setTitle:forState: . This keeps happening as far as the timer keeps firing following user's touch, every 1 second.

I handle 3 using titleForState . However here I don't get the value set in 2. Sometimes when I get correct value, there is still one problem: After touch is over, I still see in UI the same old title on that custom UIButton, not the one that I read using titleForState. (for that matter, even UIButton.textLabel.text gives wrong value)

1 - Am I following the right approach for touch and hold? (I mean using the timer approach depicted to set and read UIButton titles)

2 - If yes, what should I change in my code to read correct UIButton title value?

EDIT:

I got rid of the issue I get in 3 above. The reason for the issue was: I wasn't supplying same UIControlState combination while reading and writing. I was assuming that if you supply UIControlStateNormal | UIControlStateHighlighted UIControlStateNormal | UIControlStateHighlighted for writing title and then use UIControlStateNormal for reading it back, it should give back the currect title value, and vice versa. Unfortunately that's not the case. I changed my app logic so that I only have to use one of these states at both times.

However the main issue still remains (2 above) - how to show title while the UIButton is still in highlighted state. Title is completely invisible while the touch is held.

how to show title while the UIButton is still in highlighted state. Title is completely invisible while the touch is held.

Is your button configured such that the title disappears during a touch event, without your code changing the title text? That is with no code changing the title does it still disappear?

I think your button needs to be redrawn, try calling [button setNeedsDisplay] after changing the title text.

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