问题描述
||
我试图在
tableview
控制器的单元格中显示UILabel
文本(UIControl
的子类)。
我的代码如下:
在UIControl
标签.h文件中
#import <Foundation/Foundation.h>
@interface UIControlLabel : UIControl
{
UILabel *userNameLabel;
}
@property (nonatomic,retain) UILabel *userNameLabel;
@end
在UIControl.m
文件中
#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
在tableviewcontroller .m文件中
- (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;
}
我的问题是该单元格未显示我在上面设置的标签。我这里缺少什么吗?
解决方法
似乎您没有在课程中为UILabel设置框架。
在UILabel上调用
sizeToFit
,设置框架以匹配单元格的整体大小,使用,9ѭ或在UIControlLabel中实现-layoutSubviews
(然后您可能需要调用might11ѭ。