Domanda

Suppose an application for iOS displays an element that, when clicked, invokes a menu of actions for that element (say an UIActionSheet for example). The catch is, many clickable element such as this one may be present in every view in the application, so the action menu and its delegates must also be handled in any situation.

For example, the clickable element may be a photo of some product (UIButton with image background), that may appear in many different screens, and when clicked the user is presented with options such as "Buy", "See details", and so on.

How would you go about designing/implementing this kind of component with the associated behaviors, in a modular and reusable way?

It's important to keep the feature in a self-contained set of classes that can easily be tested separately and turned on/off when needed, and also not needing to insert code to every controller where the feature may be used.

Thanks!

È stato utile?

Soluzione

How about creating a singleton class that represents the feature you want? You can then just call the singleton object every time.

@interface MyClickableButtonWithImage : NSObject {
    UIButton *aButton;
}
+(MyClickableButtonWithImage)getInstance;
-(IBAction)buttonClicked:(id)sender;
@property (nonatomic, strong) IBOutlet UIButton *aButton;

@end

// In your .m files, this will get the singleton object
MyClickableButtonWithImage *myCBWI = [MyClickableButtonWithImage getInstance];

Altri suggerimenti

If you're implementing an app-wide UI element that can appear in more than one view, I would subclass your UIViewController (ie. ABCViewController). I usually do this at the beginning of every project just in case I need to implement something app-wide and all of my views are a subclass of that view controller with no code changes except for the one word in the header file. Then implement a function in your ABCViewController for showing the menu and a function to dismiss it. Compared to the Singleton class, I find it easier to memory manage the object and callback to the ViewController without having to deal with delegates.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top