I have created a custom class, preferring composition over inheritance and it works perfect. My custom class has a button and it knows it’s MCContact object. Also it draws a proper button and calculates frames automatically using MCContact object, that is passed.
Header file sample:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#import <UIKit/UIKit.h> @protocol MCContactViewDelegate; @interface MCContactView : UIView { } @property (nonatomic, strong) MCContact *mcContact; @property (nonatomic, weak) id <MCContactViewDelegate> delegate; - (id)initWithContact:(MCContact*)mcContact delegate:(id <MCContactViewDelegate>)delegate; @end @protocol MCContactViewDelegate <NSObject> - (void)contactViewButtonClicked:(MCContactView*)contactView; @end |
Implementation file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#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]; } @end |