سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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:

  1. Create a formatter object extending NSObject
  2. 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.

  3. 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];
        }
    }
    
  4. 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 set label.font = formater.labelFont]; If every UILabel can have a different size and font you just create a dictionary in your formater to hold that.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top