I am trying to display a UILabel
text (subclass of UIControl
) in a cell of a tableview
control开发者_开发问答ler.
My code as follows:
In UIControl
label .h file
#import <Foundation/Foundation.h>
@interface UIControlLabel : UIControl
{
UILabel *userNameLabel;
}
@property (nonatomic, retain) UILabel *userNameLabel;
@end
In UIControl.m
file
#import "UIControlLabel.h"
@implementation UIControlLabel
@synthesize userNameLabel;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
NSLog(@"in init with frame method");
self.userNameLabel = [[UILabel alloc] init];
[self addSubview: userNameLabel];
}
return self;
}
@end
In tableviewcontroller .m file
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* PlaceholderCellIdentifier = @"PlaceholderCell";
int row = [indexPath row];
Answer *thisAnswer = [self.array objectAtIndex:row];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];
UIControlLabel *control = [[UIControlLabel alloc]initWithFrame:CGRectMake(35, 10,100, 10)];
control.userNameLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.0];
control.tag = 2;
[cell.contentView addSubview:control];
}
UIControlLabel *thisControl = (UIControlLabel *)[cell.contentView viewWithTag:2];
thisControl.userNameLabel.text = [NSString stringWithFormat:@"%@",thisAnswer.userName];
return cell;
}
My issue is that the cell is not showing the label i set above. Is there something I am missing out here?
Seems like you're not setting a frame for your UILabel within your class.
Either call sizeToFit
on UILabel, set the frame to match the whole size of your cell, use autosizeMask
or implement -layoutSubviews
in your UIControlLabel (then you might need to call [cell setNeedsLayout]
.
精彩评论