I created a custom class, preferring composition over inheritance, and it works great. My custom class has a button and it knows the MCContact object. It also draws the correct button and automatically calculates frames using the MCContact object that is being transmitted.
Example header file:
Implementation File:
#import "MCContactView.h" @interface MCContactView() { UIButton *_button; } @end @implementation MCContactView - (id)initWithContact:(MCContact*)mcContact delegate:(id <MCContactViewDelegate>)delegate { self = [super initWithFrame:CGRectZero]; if (self) { GetTheme(); _mcContact = mcContact; _delegate = delegate; _button = [UIButton buttonWithType:UIButtonTypeCustom]; UIImage *normalBackgroundImage = [[UIImage imageNamed:@"tokenNormal.png"] stretchableImageWithLeftCapWidth:12.5 topCapHeight:12.5]; [_button setBackgroundImage:normalBackgroundImage forState:UIControlStateNormal]; UIImage *highlightedBackgroundImage = [[UIImage imageNamed:@"tokenHighlighted.png"] stretchableImageWithLeftCapWidth:12.5 topCapHeight:12.5]; [_button setBackgroundImage:highlightedBackgroundImage forState:UIControlStateHighlighted]; _button.titleLabel.font = [theme contactButtonFont]; [_button setTitleColor:[theme contactButtonTextColor] forState:UIControlStateNormal]; [_button setTitleEdgeInsets:UIEdgeInsetsMake(4, 6, 4, 6)]; NSString *tokenString = ([allTrim(mcContact.name) length]>0) ? mcContact.name : mcContact.eMail; [_button setTitle:tokenString forState:UIControlStateNormal]; [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; CGSize size = [tokenString sizeWithFont:[theme contactButtonFont]]; size.width += 20; if (size.width > 200) { size.width = 200; } size.height = normalBackgroundImage.size.height; [_button setFrame:CGRectMake(0, 0, size.width, size.height)]; self.frame = _button.frame; [self addSubview:_button]; } return self; } - (void)buttonClicked:(id)sender { [self.delegate contactViewButtonClicked:self]; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ @end
wzbozon
source share