根据内容的大小调整文本标签的大小

Resizing the text label based on the size of content

我读过几篇关于这个主题的帖子:UILabel - auto-size label to fit text?, , and http://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift。看来我完全按照这些帖子的建议行事,但似乎行不通。 以下是目前我的模拟器显示的内容:

我已经正确地设置了约束,我认为并且我这样写了以下内容:

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 150

}

我写道:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CathyTaskLogTableViewCell

        cell.messageLabel.sizeToFit()
        cell.messageLabel.text = "If you'd like to have more control over the way objects are synced, you can keep them in the local datastore until you are ready to save them yourself using saveInBackground. To manage the set of objects that need to be saved, you can again use a label. The fromPinWithName: method on PFQuery makes it easy to fetch just the objects you care about."

        return cell
    }

并且我已经将行 lines 设置为 0,如下所示:

对于label,我设置了所有四个约束以及宽度和高度约束。我的约束是这样的:

但是,它并没有导致我的所有台词都显示出来。对于如何解决这个问题,有任何的建议吗?提前致谢!!!

在表格视图中使用自定义单元格,然后根据字母的数量增加高度限制,它肯定会工作,因为我们遇到了一些问题。

使用下面的代码根据文本自动调整标签大小

    NSString * test=@"this is test this is test inthis is test ininthis is";

testLabel.text = test;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];
[testLabel setLineBreakMode:UILineBreakModeWordWrap];

您应该删除标签的高度并从标签底部添加新的约束到 tableview..它可能会解决您的问题 problem.Because 如果您添加标签的约束高度然后它会修复您的标签的高度如果你放置底部约束,然后无论您的内容有多少,它都会从底部放置固定像素高度。

use this it is working for  me


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   data=@[@"123454",@"122",@"thi is subbareddy",@"This is subbs reddy working as software employee trying to test dynamic heighjt for sa label"];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [data count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *cellIdentifier=@"Cell";
    CustomTableViewCell * Cell=(CustomTableViewCell*)[self.tblView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (Cell==nil) {
        NSArray *nib=[[NSBundle mainBundle]loadNibNamed:@"CustomTableViewCell" owner:self options:nil];
        Cell=[nib objectAtIndex:0];
    }
    UILabel *lblLoadId=(UILabel *)[Cell viewWithTag:1];

    lblLoadId.text=[data objectAtIndex:indexPath.row];
    lblLoadId.numberOfLines=0;
    CGFloat rowHeight = [self heightForText:lblLoadId.text];
    lblLoadId.frame = CGRectMake(0, 0, 300, rowHeight);


    return Cell;
}



- (CGFloat)heightForText:(NSString *)bodyText
{
    UIFont *cellFont = [UIFont systemFontOfSize:17];
    CGSize constraintSize = CGSizeMake(300, MAXFLOAT);
    CGSize labelSize = [bodyText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = labelSize.height + 50;
    NSLog(@"height=%f", height);
    return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *labelText =[data objectAtIndex:indexPath.row];
    return [self heightForText:labelText];
    //return 100;
}

还有一个选项,首先映射高度约束的出口,然后在 UITableView 的 heightForRow 委托方法中,计算文本的高度,然后 return 计算出的高度加上另一个正在处理的 UIElements 高度正如我在模拟器的单元格中看到的那样,在像日期和时间标签这样的单元格上使用,然后在 cellForRow 方法中再次计算文本的高度并将该高度分配给高度约束的映射对象,最后更新标签的约束,如 [your label updateConstraints] i希望有用。

这是Objective-C解决方案。

首先,在您的 constraints 中为 UILabel 设置的高度值 >= 任何值(例如设置高度限制 >= 44),请参见附图。

在您的控制器中添加以下方法以获取字符串文本的 height

- (CGSize)getHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
    CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
    size = CGSizeMake(frame.size.width, frame.size.height);
}
return size;

}

在上述方法中,font 只不过是您用于标签的字体。

覆盖 tableview 的 heightForRowAtIndexPath ,如下所示,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return [self getHeightForText:[self.valuesArray objectAtIndex:indexPath.row] havingWidth:323.0f andFont:[UIFont fontWithName:@"Helvetica" size:18.0f]].height;

}

cellForRowAtIndexPath 方法中,以正常方式将文本设置为标签。此标签将根据文本的大小自动展开;

如果您想在默认 table 视图单元格中添加自定义标签,请使用此选项。

我们要解决的问题。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     
     if var cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") {

       self.customCellLabelTitle = {
                    let lbl = UILabel(frame: CGRect(x: 90, y: cell.textLabel?.frame.origin.y ?? 2, width: self.tblView.frame.size.width - 90, height: 40))
                    lbl.translatesAutoresizingMaskIntoConstraints = false
                    lbl.numberOfLines = 0
                    lbl.setContentCompressionResistancePriority(.required, for: .horizontal)
                    lbl.backgroundColor = .clear
                    lbl.text = "cell text value"
                    lbl.adjustsFontSizeToFitWidth = true
                    lbl.minimumScaleFactor = 0.01
                    return lbl
                }()

}
 

输出: