Reputation: 3442
I want to create a custom class RoundedImageView by subclassing the UIImageView
class.
In order to make it round, I use the following code:
self.layer.cornerRadius = self.frame.size.width/2;
self.layer.masksToBounds = YES;
Where should I place this code? In the initializer? Or maybe in layoutSubviews
? I know there's not a good idea to access properties from self within the initializer(because self may not be fully initialized), that is why I am confused and I'm not sure where to place this code.
Upvotes: 0
Views: 76
Reputation: 69047
The initialisation method is definitely the right place, since you want to set those properties only once.
About your concern related to acessing properties, the idea is that a property accessor could be overridden in a derived class and thus access portions of the object not already properly initialised. This is not a great concern in your case, I would say, unless you plan to override layer
's getter in some not fully sensible ways.
Upvotes: 1
Reputation: 34839
The canonical initialization for a UIView (or any class derived from UIView) looks like this
- (void)setup
{
// do any initialization here
}
- (void)awakeFromNib
{
[self setup];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
[self setup];
return self;
}
This works for views that are created by storyboard and views that are created programmatically. Source: the CS193P videos.
Upvotes: 1