Jacob Smith
Jacob Smith

Reputation: 813

How to create a table like spreadsheet in Swift?

I needed to create table spreadsheets like excel. And they will be in a TableViewController's cells. So there will be multiple spreadsheets in different cells. Example:

Example spreadsheet

My first approach was to create nested UICollectionViews. However it slowed the UI heavily. It seems like using UICollectionView is bad for performance. This is how I implemented it anyway:

        let table = UIStackView()
        table.axis = .Vertical
        table.spacing = 8

        let json = JSON(data: jsonNew)

        for i in 0..<json["Rows"].count{

            let horizontal = UIStackView()
            horizontal.axis = .Horizontal
            horizontal.spacing = 8

            for j in 0..<json["Rows"][i]["Column"].count{

                let label = UILabel()
                label.text = json["Rows"][i]["Column"][j].string!
                label.lineBreakMode = .ByWordWrapping
                label.numberOfLines = 0
                label.font = label.font.fontWithSize(12)
                horizontal.addArrangedSubview(label)

            }

            table.addArrangedSubview(horizontal)

        }

        parent.addSubview(table)
        return table

The question is, is there any other way to implement this kind of table in a better way?

Upvotes: 8

Views: 18068

Answers (1)

mz2
mz2

Reputation: 4702

A stack of collection views constructed like in your example would have terrible performance because you eagerly construct the whole hierarchy – there's vertically no cell reuse based on where your screen is in a potentially very tall table.

A custom collection view layout would strike as one natural way to accomplish this. Perhaps the code in KEZCollectionViewTableLayout could work as inspiration? There's also MMSpreadsheetView.

You may also find this blog post interesting.

(There is a related question on how to specifically accomplish this using UICollectionView.)

Upvotes: 9

Related Questions