iphone - Shared action for many UIButtons, get button-specific string -
i have view containing number of uibuttons "tom , jerry", "the lion king", etc. want of them invoke same action in view controller, , differentiate between different buttons button-specific nsstring (e.g. identifiers "tomjerry", "lionking").
ideas:
- abuse buttons' title text property (custom button style, clear text color).
- would work, feels dirty… (and works if button doesn't need display text.)
- subclass uibutton ivar + property "context".
- great adding buttons programmatically,
- but: view loaded nib, have define outlet every button (and set context property in awakefromnib or viewdidload). bleh…
- create subclass each button different "-(nsstring*)context" method implementations.
- ugh… seriously? ;-)
- use tags identify buttons , dictionary mapping tags button-specific strings.
- dry violation: tag need known/specified twice – in nib identify button, , in dictionary retrieve corresponding string.
- i have far avoided using tags. maybe opportunity start?
how best achieve this? ideas, best-practices, implementation patterns?
update: after reading first answers (thanks!), believe should add points clarification.
all of above approaches should work; point is, don't particularly like of them. asking of approaches favor (and why), or whether there other better approaches.
further "requirements":
- i don't want connect each button outlet.
- i want retrieve button-specific string in generic fashion, i.e. no switch on action sender à la
if (sender==self.button1) {…} else if (sender==self.button2) {…}
added
option create category of uibutton adding method returns nsstring based on tag. you've still got potential tag trouble tag-to-string conversion -- actual , conceptual -- in 1 place.
i believe meets original , further requirements.
previously
tags fast , light, comparing 2 integers.
you can create numbering scheme keeps things cleanly separated: 1000-1999 type of thing, 1000-1099 subgroup, 1015 instance, etc.
numeric comparisons available: x.tag > 10000 this.
obviously, though, means have track , code end difficult parse down road. still, nifty advantages.
Comments
Post a Comment