【发布时间】:2011-07-02 03:16:18
【问题描述】:
我有一个包含 3 个 UILabel 的自定义单元格。最后一个标签将包含嵌入 \n 的文本,以便该单元格中的数据每行列出一项。我知道所需的行数,并且我知道每行需要 15 像素高。我必须更改此标签大小的代码在这里:
//Set up the cell
static NSString *CellIdentifier = @"Cell";
CustomHistoryCell *cell = (CustomHistoryCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomHistoryCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.probeInfo.lineBreakMode = UILineBreakModeWordWrap;
cell.probeInfo.numberOfLines = 0;
cell.probeInfo.text = theProbes;
[cell.probeInfo setAdjustsFontSizeToFitWidth:YES];
CGRect newFrame = cell.probeInfo.frame;
newFrame.size.height = nAdditionalLabelHeight*15;
cell.probeInfo.frame = newFrame;
theProbes 包含带有 \n 的文本,nAdditionalLabelHeight 包含行数。我已将背景颜色设置为灰色,以便我可以查看标签的大小是否正确并且不会改变它的高度。谁能看到我做错了什么?
以下是自定义单元格 .h 文件的代码,以防万一:
@interface CustomHistoryCell : UITableViewCell {
UILabel *_stokerName;
UILabel *_smokeDateTime;
UILabel *_probeInfo;
}
@property (nonatomic,retain) UILabel *stokerName;
@property (nonatomic,retain) UILabel *smokeDateTime;
@property (nonatomic,retain) UILabel *probeInfo;
@end
这是自定义单元格 .m 文件的代码,以防万一:
#import "CustomHistoryCell.h"
@implementation CustomHistoryCell
@synthesize stokerName = _stokerName;
@synthesize smokeDateTime = _smokeDateTime;
@synthesize probeInfo = _probeInfo;
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
{
// Initialization code
self.stokerName = [[UILabel alloc]init];
self.stokerName.textAlignment = UITextAlignmentLeft;
self.stokerName.font = [UIFont boldSystemFontOfSize:20];
self.smokeDateTime = [[UILabel alloc]init];
self.smokeDateTime.textAlignment = UITextAlignmentLeft;
self.smokeDateTime.font = [UIFont systemFontOfSize:12];
self.probeInfo = [[UILabel alloc]init];
self.probeInfo.textAlignment = UITextAlignmentLeft;
self.probeInfo.font = [UIFont systemFontOfSize:12];
self.probeInfo.backgroundColor = [UIColor grayColor];
[self.contentView addSubview:self.stokerName];
[self.contentView addSubview:self.smokeDateTime];
[self.contentView addSubview:self.probeInfo];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+5,5, 300, 25);
self.stokerName.frame = frame;
frame= CGRectMake(boundsX+5,30, 300, 15);
self.smokeDateTime.frame = frame;
frame= CGRectMake(boundsX+5,45, 300, 15);
self.probeInfo.frame = frame;
}
- (void)dealloc
{
[super dealloc];
}
@end
【问题讨论】:
-
我删除了昨天留下的答案,希望您能获得更好(即正确)的答案。我唯一能想到的另一件事是
setAdjustsFontSizeToFitWidth:仅在numberOfLines= 1 时才有效,但即便如此我也不确定为什么或如何影响 UILabel 的帧大小。
标签: iphone cocoa-touch uilabel