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.
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.
I'm not sure I totally understand the question, but you can use the
sizeToFit
method on aUILabel
(the method is inherited fromUIView
) to change the size according to the label text.The easiest way to find the no. of lines depending on text. You can use this code:
it returns some float value.
In Swift:
In Objective C
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 calledUILabel.swift
with the following code:2) In your app code, define the label width you want and just call
resizeToText()
:This will maintain width while increasing the height automatically.
try bellow code, it works for multiline