You can add additional properties to a category of an object using associated objects. it's to be used with caution but take a look here.
Make all controls to posses some additional properties and methods?
Domanda
My application is a form-designing application (the user can design their own form) so I want the like UITextField
, UItextView
, UIButton
, UIImageView
, etc. to posses some additional properties and methods. I know that I can subclass each control and add desired properties and methods. But I feel there may be some other easier way to achieve this.
Are there any other ways or is subclassing each control is the only way?
Soluzione
Altri suggerimenti
I think what you are trying to do is apply a theme to controls based on user choices. I don't think you need to change the elements themselves but apply a theme concept. The best solution I have found is to create an object that handles formatting, the user's choice and more. This is how I think you can implement it:
- Create a formatter object extending NSObject
Have a property for each changeable piece of the theme:
for example if the size of controls changes you can have a CG element in there. If the font color changes you have a UIFont property in there.
create a shared instance of your formater by adding:
+(Formater *) sharedInstance; //add to .h + (Formater *) sharedInstance //add to .m { if (!_sharedInstance) { _sharedInstance = [[Formater alloc] init]; } }
Now you can call the shared instance of the formater and use it's properties to set the properties of your elements. For example: If a user picked that UILabels should be of fontX and size 10. You set
formater.labelFont = [UIFont fontWithName: fontX size:10];
. Then every time you have a label you just setlabel.font = formater.labelFont];
If every UILabel can have a different size and font you just create a dictionary in your formater to hold that.