On iOS, how to make a dynamic list of "links" or buttons to call a method with a string argument?

It seems like the usual way to make text behave like an iOS link is to make UIButton, but I noticed that the UIButton addTarget or gestureRecognizer addTarget have no argument that can be passed to the method when the button is clicked?

The situation is that from the server we can return a list of words such as "pineapple", "apple", "orange", and the numbers can change. These words are displayed on the screen, and clicking on the word will call the ViewController to replace the main view controller.

It seems that one way is to use the UIButton tag, so when we configure the button, we give it the 0 tag, and in another array of the current view or view controller, we make the 0 element a point for the NSString object containing the word "pineapple". And so in the handler, the tag can be retrieved, and it can be used to retrieve the string. But this is the only way, because it does not seem very structural. Is there a better way?

+4
source share
2 answers

My knee jerk responded simply to suggest that you subclass UIButton . Whenever you want to add a property to an existing class, a “subclass” is the first answer that comes to mind. But when I tried to subclass UIButton , it did not work. Search for a “UIButton subclass” I found this to be a well-known issue with a few recommended solutions:

I tried to create a category with associative links , and also simplify the approach to a simple subclass of UIView instead and make the desired button a preview of what. Both approaches work fine. But the intuitively attractive variant of a simple subclass of UIButton does not work.

But while the various work tasks for adding properties to UIButton objects work, they seem unintuitive enough that I would tend to go back to something simple, like using tag numbers in an array or a dictionary, rather than chasing these bulky button subclassing methods .

+1
source

Create a mutable dictionary. To associate a word with a button, add the address of the buttons wrapped in nsnumber as a key and the word as an object. When the button is pressed and sends an action message along with "sender", you can get the current word from the dictionary.

0
source

Source: https://habr.com/ru/post/1435715/


All Articles