Reputation: 13
this question is about "style", because i think this is a very common problem and i'm looking for an elegant solution. I have created some "advanced" UIView and i try to make them very customizable. Usually i create the UIView structure inside a custom init method, but i need to know the value of all customizable parameter inside init method so sometimes i need a very long init method like:
initWithFrame:color:font:verticalspace:verylonglist:
I tried to use delegate design pattern but i need also to pass delegate inside init method.
My actual best solution is to leave empty the init method and move everything about layout inside a "configure" method. everytime i chance a property like background color or font i will call this method and i will rebuild the view.
I think there is a best way to solve this problem... I'd be curious to see the code of UITableView Class, because with that class you can pass a delegate outside init method.
Upvotes: 0
Views: 92
Reputation: 10782
Check out something like a UIButton
or UILabel
. They both have tons of configurable aspects, however to simply create an instance of one of those objects, they need very little information.
In general, provide init methods that allow the consumer of your class to specify the least amount of information for the class to work.
If you do want to give the consumer a way to initialize the class with a bunch of values, consider using some sort of initWithDictionary:
method that takes an NSDictionary
of parameters. This keeps your method names short and allows the user to customize an arbitrary number of settings for your class.
You could also consider providing a way for the consumer to request an instance with some standard set of values. UITableViewCell
, for example, has an initWithStyle:reuseIdentifier:
method. The important part is the style - UITableViewCell
provides several default styles like UITableViewCellStyleDefault
and UITableViewCellStyleSubtitle
.
Upvotes: 2
Reputation: 18507
I don't know if it is the standard/best practices way but I use a dictionary in cases like this and pass that to an initWithDictionary
initializer. Would be possible too to create a class method that returns a 'default settings' type dictionary which can then be customized (and delegate set), so that not every param needs to be specified whenever the class is used.
Upvotes: 0