Skip to content

Instantly share code, notes, and snippets.

@mikeseif
Last active December 24, 2015 08:29
Show Gist options
  • Save mikeseif/6770561 to your computer and use it in GitHub Desktop.
Save mikeseif/6770561 to your computer and use it in GitHub Desktop.
Accessor pattern for iOS properties, UILabel example.
- (UILabel *)lblTitle
{
// Check if the property isn't instantiated yet
if (_lblTitle == nil) {
_lblTitle = [[UILabel alloc] init];
// Disable auto-constraints if you plan to implement your own
[_lblTitle setTranslatesAutoresizingMaskIntoConstraints:NO];
/* Set any one time configuration properties for the label here
like font / size, color, background, etc.
*/
}
/* Determine if the view exists in the hierarchy and add if not.
Substitute self.view with the desired parent view.
*/
if (![[self.view subviews] containsObject:_lblTitle]) {
/* If not using AutoLayout, you should probably set a
frame here.
*/
[self.view addSubview:_lblTitle];
/* Add your NSLayoutConstraints here if you plan to use them
*/
}
return _lblTitle;
}
// ...
/* Anywhere else you can refer to the property with self.lblTitle
and it will be checked for nil / in the view hierarchy.
If you don't need to configure anything outside of the accessor,
a simple call to [self.lblTitle setNeedsDisplay] will be sufficient
to instantiate and attach the subview.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment