I have taken UIlabel which are generated dynamically using for loop, each type diff text is assign in label, I want to give UILabel size dynamically depending on text.
let label:UILabel = UILabel()
label.textColor=UIColor.black
label.font = UIFont(name: "Halvetica", size: 17)
label.numberOfLines = 1
label.text = item.name
label.sizeToFit()
label.frame = CGRect(x: 5, y: imageView.frame.height+10, width: 50, height:label.frame.height)
get a label height depending on it's text, font, and width you assign to it:
func rectForText(text: String, font: UIFont, maxSize: CGSize) -> CGSize {
let attrString = NSAttributedString.init(string: text, attributes: [NSFontAttributeName:font])
let rect = attrString.boundingRectWithSize(maxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
let size = CGSizeMake(rect.size.width, rect.size.height)
return size
}
let labelSize = rectForText("your text here", font: UIFont.systemFontOfSize(your font), maxSize: CGSizeMake(your label width,999))
let labelHeight = labelSize.height //here it is!
NSString(string: "hello this is a string").boundingRect(
with: CGSize(width: width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: self],
context: nil).size
Use this method to get determine the size for you string. Put maximum height and maximum width in CGSize(widhth,height)
and it will return CGSize
object containing height and width. Use it according with your scenario
myLabel.text = "Your Label Text Here"
myLabel.textAlignment = .Natural
myLabel.numberOfLines = 0
myLabel.sizeToFit()
myLabel.frame = CGRectMake(myLabel.frame.origin.x, myLabel.frame.origin.y, 280, myLabel.frame.height)
Create Extension to calculate the height of label following method return height of the label
import UIKit
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 60)
let label:UILabel = UILabel(frame: CGRectMake(x, y, width, height))
label.numberOfLines = 4
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
let font = UIFont(name: "Helvetica", size: 20.0)
label.font = font
label.text = "Whatever you want the text enter here"
label.sizeToFit()
If you want to set numberOfLines according to the content of text,give your maximum lines.That is very important here.