UILabel auto resize on basis of text to be shown

2019-03-07 17:10发布

I'm working on an application, in which I'm required to autoresize the text area on basis of text to be displayed.

Firstly, I'm not sure for this either I should use UILabel (Logically is the best choice for displaying static text, which is in my case) or UITextView.

How I wish to use it?
I want to simply init my Label or text view for that matter with Text. Instead I define the frame first and then restrict my text in that area.

If you can suggest the right solution, that will be a great help.

I went through documentation and other references but didn't find much which could help me here or I could've overlooked it.

10条回答
别忘想泡老子
2楼-- · 2019-03-07 17:49

Please note that with autolayout call sizeToFit won't change size, because it will be changed later by autolayout calculations. In this case you need to setup proper height constraint for your UILabel with "height >= xx" value.

查看更多
甜甜的少女心
3楼-- · 2019-03-07 17:50

I'm not sure I totally understand the question, but you can use the sizeToFit method on a UILabel (the method is inherited from UIView) to change the size according to the label text.

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-07 17:54

The easiest way to find the no. of lines depending on text. You can use this code:

ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300); 

it returns some float value.

[lbl setNumberOfLines:floatvalue];
查看更多
Juvenile、少年°
5楼-- · 2019-03-07 17:55

In Swift:

testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))
testLabel.text = test
testLabel.numberOfLines = 0
testLabel.sizeToFit()

In Objective C

UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];
testLabel.text = test;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];
查看更多
我想做一个坏孩纸
6楼-- · 2019-03-07 17:59

Because you're going to use this solution countless times in your app, do the following:

1) Create a directory called extensions and add a new file inside called UILabel.swift with the following code:

import UIKit

extension UILabel {
    func resizeToText() {
        self.numberOfLines = 0
        self.sizeToFit()
    }
}

2) In your app code, define the label width you want and just call resizeToText():

label.frame.size.width = labelWidth
label.resizeToText()

This will maintain width while increasing the height automatically.

查看更多
forever°为你锁心
7楼-- · 2019-03-07 17:59

try bellow code, it works for multiline

self.labelText.text = string;
self.labelText.lineBreakMode = NSLineBreakByWordWrapping;
self.labelText.numberOfLines = 0;
查看更多
登录 后发表回答