Ios 以编程方式基于文本长度的自定义UILabel宽度
我想创建一个Ios 以编程方式基于文本长度的自定义UILabel宽度,ios,objective-c,uilabel,Ios,Objective C,Uilabel,我想创建一个UILabel,它比同一UILabel中的文本宽度稍宽一点。我检查了很多问题并尝试了他们的答案,但仍然找不到正确的方法。我可以得到文本的宽度,但无法重画框架 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object { static NSString *Cell = @"cell";
UILabel
,它比同一UILabel
中的文本宽度稍宽一点。我检查了很多问题并尝试了他们的答案,但仍然找不到正确的方法。我可以得到文本的宽度,但无法重画框架
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *Cell = @"cell";
LikeActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
cell.lbl.backgroundColor = [UIColor colorWithRed:7.0 green:4.0 blue:55.0 alpha:0.7];
NSString *lblString = [NSString stringWithFormat:@"%@", object[@"content"]];
cell.lbl.text = lblString;
float widthIs = [cell.lbl.text
boundingRectWithSize:cell.lbl.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:cell.lbl.font }
context:nil]
.size.width;
float heightIs =
[cell.lbl.text
boundingRectWithSize:cell.lbl.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:cell.lbl.font }
context:nil]
.size.height;
NSLog(@"CELL TEXT WIDTH %f", widthIs);
int x = widthIs + 10;
int y = heightIs;
// ATTEMPT 1
[cell.lbl setFrame:CGRectMake(0,0,x,cell.lbl.frame.origin.y)];
// ATTEMPT 2
cell.lbl.frame = CGRectMake(0, 0, x, cell.lbl.frame.origin.y);
return cell;
}
当我运行这些行时,什么都没有发生,标签没有改变,我不能理解,因为它应该改变 在标签上创建固定宽度和固定高度约束(通过interface builder),将其公开给视图控制器(同样,通过interface builder),并直接操作布局约束:
// in the .h created by interface builder
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelHeight;
您可以使用自动布局使标签的宽度环绕文本。如果文本只有一行,并且希望标签大小适合该行,则只需添加设置前导属性或中心X(以及顶部/中心Y和高度的约束)的约束,并确保添加
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
[yourLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
将其添加到子视图后。如果文本是多行的,或者可以是多行的,则需要多行代码。您需要设置垂直轴的压缩阻力和拥抱
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[yourLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
还加
- (void)layoutSubviews {
if (!CGRectIsEmpty(self.frame)) {
_featureDescriptionLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentView.frame)-59-5;
}
[super layoutSubviews];
}
这将进入自定义表视图单元格中。将“最大布局宽度”设置为文本在单元格内的最大宽度
另外,如果它是多行的,请不要忘记将行数设置为0。帧设置无效,因为“自动布局”处于启用状态,请尝试在设置其帧时将标签的
自动调整大小GMaskintoConstraints
属性设置为YES
,或者您可以关闭“自动布局”。及
[cell.lbl setFrame:CGRectMake(0,0,x,cell.lbl.frame.origin.y)]代码>应该是
[cell.lbl setFrame:CGRectMake(0,0,x,heightIs)]代码>尝试下面的cellForRow和获取文本大小的方法。希望这对你有用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* cellIdentifier = @"CellIdentifier";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
UILabel *lblComment;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
lblComment=[[UILabel alloc] init];
lblComment.backgroundColor=[UIColor clearColor];
lblComment.font=[UIFont fontWithName:FONT_NAME size:FONT_SIZE];
lblComment.numberOfLines=0;
lblComment.lineBreakMode=NSLineBreakByWordWrapping;
[cell.contentView addSubview:lblComment];
}else{
lblComment=(UILabel *)[[cell.contentView subviews] objectAtIndex:0];
}
lblComment.tag=[self realRowNumberForIndexPath:indexPath inTableView:tableView] + 0;
CGSize Comment_Size = [self GetLAbelSize:lblComment.text LabelFont:FONT_NAME width:FONT_SIZE];
lblComment.frame = CGRectMake(lblComment.frame.origin.x, lblComment.frame.origin.y, Comment_Size.width, Comment_Size.height);
return cell;
}
-(CGSize)GetLAbelSize:(NSString *)str_Text LabelFont:(UIFont *)font width:(float)width
{
CGSize constraintSize = CGSizeMake(width,MAXFLOAT);
// CGSize labelSize = [str_Text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect boundingRect = [str_Text boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
CGSize labelSize = boundingRect.size;
return labelSize;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGSize lblComment = [self GetLAbelHeight:[array_Comment objectAtIndex:indexPath.row] LabelFont:FONT_NAME width:FONT_SIZE];
float totalHeight = lblComment.height+5;
return totalHeight;
}
- (NSInteger)realRowNumberForIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView
{
NSInteger retInt = 0;
if (!indexPath.section)
{
return indexPath.row;
}
for (int i=0; i<indexPath.section;i++)
{
retInt += [tableView numberOfRowsInSection:i];
}
return retInt + indexPath.row;
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
静态NSString*cellIdentifier=@“cellIdentifier”;
UITableViewCell*单元格=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
UILabel*lblComment;
如果(单元格==nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault重用标识符:cellIdentifier];
lblComment=[[UILabel alloc]init];
lblComment.backgroundColor=[UIColor clearColor];
lblComment.font=[UIFont fontWithName:font\U NAME size:font\U size];
lblComment.numberOfLines=0;
lblComment.lineBreakMode=NSLineBreakByWordWrapping;
[cell.contentView addSubview:lblComment];
}否则{
lblComment=(UILabel*)[[cell.contentView子视图]objectAtIndex:0];
}
lblComment.tag=[self-realRowNumberForIndexPath:indexPath inTableView:tableView]+0;
CGSize Comment_Size=[self-GetLAbelSize:lblComment.text-LabelFont:FONT\u-NAME-width:FONT\u-Size];
lblComment.frame=CGRectMake(lblComment.frame.origin.x,lblComment.frame.origin.y,注释大小.宽度,注释大小.高度);
返回单元;
}
-(CGSize)GetLAbelSize:(NSString*)str_Text LabelFont:(UIFont*)字体宽度:(float)宽度
{
CGSize constraintSize=CGSizeMake(宽度,最大浮点);
//CGSize labelSize=[str_文本大小WithFont:font constrainedToSize:ConstrainetSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect boundingRect=[str_Text BOUNDINGRECTINGWITHSIZE:constraintSize选项:NSStringDrawingUseLineFragmentOrigination属性:@{NSFontAttributeName:font}上下文:nil];
CGSize labelSize=boundingRect.size;
返回标签化;
}
-(CGFloat)tableView:(UITableView*)表视图行高度索引路径:(NSIndexPath*)索引路径{
CGSize lblComment=[self-GetLAbelHeight:[array\u Comment objectAtIndex:indexath.row]LabelFont:FONT\u NAME-width:FONT\u-SIZE];
浮动总高度=LBL建议高度+5;
返回总高度;
}
-(NSInteger)realRowNumberForIndexPath:(NSIndexPath*)indexPath inTableView:(UITableView*)tableView
{
NSInteger-retInt=0;
如果(!indexPath.section)
{
返回indexath.row;
}
对于(int i=0;i有一个非常好的教程,用于根据tableView的内容计算其动态高度。这里扩展/自定义UILabel以适应动态内容
检查这个是否有用
UILabel *type;
type.frame=[self calculateHeightOfTextFromWidth:type withText:type.text];
-(CGRect) calculateHeightOfTextFromWidth:(UILabel*)detailLabel withText:(NSString*)text {
CGRect currentFrame = detailLabel.frame;
CGSize max = CGSizeMake(detailLabel.frame.size.width, 500);
CGSize expected = [text sizeWithFont:detailLabel.font constrainedToSize:max lineBreakMode:detailLabel.lineBreakMode];
currentFrame.size.height = expected.height;
return currentFrame;
}
假设您创建自定义单元格,如:
@implementation LikeActivityTableViewCell
-(id)init{
self = [super init];
if(self){
self.lbl = [[UILabel alloc] init];
self.lbl.font = [UIFont fontWithName:@"Arial" size:16]; // Set the font you want
self.lbl.backgroundColor = [UIColor colorWithRed:7.0/255 green:4.0/255 blue:55.0/255 alpha:0.7]; // Dont forget "/255"
[self.contentView addSubview:self.lbl];
}
return self;
}
@end
那就试试:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *Cell = @"cell";
LikeActivityTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:Cell];
if(!cell){
cell = [[LikeActivityTableViewCell alloc] init];
}
cell.lbl.text = [NSString stringWithFormat:@"Am I cell number %d? No!", indexPath.row * 8]; // Put your text here
CGSize labelSize = [self getFrameForLabel:cell.lbl];
labelSize.width += 10.f;
cell.lbl.frame = CGRectMake(cell.contentView.frame.size.width * 0.5f - labelSize.width * 0.5f,
cell.contentView.frame.size.height * 0.5f - labelSize.height * 0.5f,
labelSize.width,
labelSize.height); // I decided to center the label but you can put 0, 0 as origin
return cell;
}
-(CGSize)getFrameForLabel:(UILabel*)label{
NSDictionary *attributes = @{NSFontAttributeName: label.font};
return [label.text sizeWithAttributes:attributes];
}
下面是一个方法,该方法应根据高度和文本字符串返回UILabel宽度的正确宽度。使用此方法返回的宽度设置单元格框
CGFloat *maxWidth = the maximum width you would want your label to be
CGFloat *labelHeight = the height of your label
CGFloat *additionalWidthBuffer = any fixed extra width on your label
-(CGFloat)labelHeightForText:(NSString*) text
{
UIFont * font = [UIFont systemFontOfSize:15.0f];
CGFloat width = [text boundingRectWithSize:CGSizeMake(maxWidth, labelHeight) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName: font} context:nil].size.width;
return height + additionalWidthBuffer;
}
创建一个自定义UITableViewCell。我们将其称为CustomCell。为CustomCell创建一个XIB、.h和.m。在XIB中,拖出一个表视图单元格,使其成为视图中的唯一内容。在单元格中添加标签和任何其他视图。以任何有意义的方式向视图添加约束,并确保其中一个约束为标签上的宽度约束。将此约束和标签连接到CustomCell.h。您的CustomCell.h如下所示:
@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelWidth;
@end
现在,您可以将CustomCell从XIB复制/粘贴到要在其中使用该单元格的表中。然后在CellForRowatineXpath:
中,您可以按如下方式调整标签的宽度,CustomCell中的其他视图将相应地调整(谢谢,autolayout!)
在其“layoutSubviews”方法中使用自定义UITableViewCell类和setframe
`-(无效)布局子视图{
[super layoutSubviews];
[self.lbl setFrame:...];
}`最好的方法是为UILabel
应用适当的自动布局约束。然后,如果目标是iOS 8,则将tableview的行高属性设置为UITableViewAutomaticDimension
。
或
将高度约束设置为表格视图
并在视图中显示
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height;
在视图中将布局子视图
获取tableViewCell
对象
CGFloat width = label.bounds.size.width;
if ( label.preferredMaxLayoutWidth != width )
{
label.preferredMaxLayoutWidth = width;
[tableViewCell setNeedsLayout];
[tableViewCell layoutIfNeeded];
}
如果您的自动布局约束没有问题,那么这应该可以完成任务。我成功地将
[super layoutSubviews];
[self.lbl setFrame:...];
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height;
CGFloat width = label.bounds.size.width;
if ( label.preferredMaxLayoutWidth != width )
{
label.preferredMaxLayoutWidth = width;
[tableViewCell setNeedsLayout];
[tableViewCell layoutIfNeeded];
}