It seems that a common way to make a text behave like a link on iOS is to make it a UIButton, but I noticed the UIButton’s addTarget or gestureRecognizer’s addTarget both don’t have an argument that can be passed to the method when the button is pressed?
The situation is, from a server, we may get back a list of words, such as “pineapple”, “apple”, “orange”, and the numbers can vary. These words are displayed on screen, and pressing the word will invoke a ViewController to replace the main view controller.
It seems that one way is to use UIButton’s tag, so when we set up the button, we give it a tag of 0, and in another array of the current view or view controller, make element 0 point to an NSString object, containing the word “pineapple”. And so in the handler, the tag can be obtained, and it can be used to retrieve the string. But is this the only way, because it seems not very structural. Is there a better way?
My knee-jerk answer was to simply suggest that you subclass the
UIButton. Whenever you want to add a property to an existing class, “subclass” is the first answer that comes to mind. But when I tried subclassing theUIButton, it did not work well. Searching for for “UIButton subclass” I discover that this is a well known issue with several recommended solutions:I’ve tried both creating a category with associative references as well as the simplistic approach of just subclassing a
UIViewinstead, and make the desired button a subview of that. Both approaches work fine. But the intuitively attractive option of just subclassingUIButtondoes not work well.But while the various work-arounds for adding properties to
UIButtonobjects work, they seem sufficiently unintuitive that, I’d be inclined to go back to something simple, such as using thetagnumbers in an array or dictionary, rather than pursuing these cumbersome button subclassing techniques.