Reputation: 2730
Simple question: what is the standard method of creating a customized version of say a UILabel, UIButton, etc. such that I can easily use it in multiple places? Is it simply to extend the appropriate class:
import UIKit
class FormField: UITextField {
override init()
{
super.init()
// borderStyle = UITextBorderStyle.None
}
}
Basically just want to get some default values set for some UI objects so I can easily drop them into the interface when necessary. Not really sure how to get this working.
Upvotes: 0
Views: 70
Reputation: 299355
It is very rare to subclass something like UILabel
.
The most common approach is a HAS-A pattern, where you let a controller (often a UIViewController
) manage the view for you and you reuse that. Alternately, you may make a UIView
that contains the view you want to customize, and customizes it for you (passing along things that need to be passed along).
You can also have a "configure my view this way" function that you can call on an existing standard view. I haven't seen this very often in reusable code. My experience is that these kind of configuration functions turn out to be very app specific, but they're reasonable common.
Things like UITextField
have delegate methods already, and a common way to customize them is to create a reusable delegate that applies certain behaviors.
It depends of course on what you're trying to achieve, but subclassing is pretty far down on the list of patterns, unless it's a class explicitly designed and documented to be subclassed (like UIView
or UIViewController
).
Upvotes: 2
Reputation: 453
UIView
and its subclasses have two designated initializers, -initWithFrame:
and -initWithCoder:
. The first is for programmatic instantiation while the latter is for views being unpacked from a Storyboard or NIB. Because of this, the common pattern for subclassing UIView
subclasses is the following (I'm using ObjC but the Swift code should be easy to figure out):
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self) {
[self commonInit];
}
return self;
}
- (void)commonInit {
// Do your special setup here!
}
Then, if you're using the views in Interface Builder, go to the Identity tab on the right-assistant-editor-sidebar, and in the top box where it says UILabel
or UIButton
, put in your custom button class name.
Hopefully this clears things up a bit.
Upvotes: 1