Search code examples
iosswiftuilabelword-wrapprogrammatically-created

iOS: Create Label Programmatically with Word Wrap


I am wanting to create a label programmatically that is able to word wrap for long sentences. Here is the loop I have for creating the labels:

        for i in 0..<servicesLength
    {
        let label = UILabel(frame: CGRectMake(0, number, servicesScroll.bounds.size.width - 42, 25))
        label.lineBreakMode = .ByWordWrapping
        label.numberOfLines = 0
        label.font = UIFont(name: label.font.fontName, size: 25)
        label.text = servicesList[i]
        self.servicesScroll.addSubview(label)
        number = number + 50

    }

This doesnt work though. From what I've read, in order for the wrapping to work, you need to either not set the height or make the height large enough for the content. I have to set the height for the frame and I don't want to make it extremely large for large sentences so how can I get this to work by setting everything programmatically?


Solution

  • I decided on using a TableView instead. It gave me exactly what I was looking for. If you are needing a list of sentences displayed and need word wrap for possibly large sentences or paragraphs, a tableview is much easier than messing around with adding labels programmatically. Here are the steps I followed:

    1. Follow this tutorial on how to make a tableview in Swift.
    2. Add cell.textLabel?.numberOfLines = 0 to the function that creates the cells in order to get word wrap.
    3. Add yourtableview.estimatedRowHeight = whateveryouwant yourtableview.rowHeight = UITableViewAutomaticDimension in your viewDidLoad in order to get variable heights for your rows.