I.G.
I.G.

Reputation: 11

Add UILabels with different width side by side programmatically

I want to add multiple UILabels programmatically side by side to a TableViewCell. The UILabels have different width.

The first cell in the picture shows the problem and the second cell what I would like to do.

In this example I want to add four UILabels to a TableViewCell. But the width of the TableViewCell is smaller than the width of the UILabels. Therefore I must increase the CellHeight and add the UILabels below to the other UILabels (like the second cell in the picture).

enter image description here

Upvotes: 1

Views: 1224

Answers (2)

Tejas Ardeshna
Tejas Ardeshna

Reputation: 4371

You should put UICollectionView inside of a row of your UITableViewCell. Each cell of your UICollectionView will have a multi UILabel. Update the dataSource for your UICollectionView depending on your label count. Set isScrollEnabled false of that UICollectionView and set automatic row height for UITableViewCell.

Also, set flow layout to UICollectionView :

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSizeMake(1, 1) }

Adjust cell size like below:

func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {


        let size: CGSize = keywordArray[indexPath.row].size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
        return CGSize(width: size.width + 45.0, height: keywordsCollectionView.bounds.size.height)
    }

Upvotes: 3

Gregga17
Gregga17

Reputation: 168

At first you have to make for labels.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

        let label1 = UILabel(frame: CGRect(x: 5, y: 5, width: 100, height: 25))
        label1.text = "Label 1"
        let label2 = UILabel(frame: CGRect(x: 110, y: 5, width: 225, height: 25))
        label2.text = "Label 2"
        let label3 = UILabel(frame: CGRect(x: 5, y: 40, width: 100, height: 25))
        label3.text = "Label 3"
        let label4 = UILabel(frame: CGRect(x: 110, y: 40, width: 225, height: 25))
        label4.text = "Label 4"
        cell.addSubview(label1)
        cell.addSubview(label2)
        cell.addSubview(label3)
        cell.addSubview(label4)

    return cell
}

Each label has different width and different position. You can play with it

Upvotes: 0

Related Questions