Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
Jacob Smith Avatar asked May 16 '16 08:05

Jacob Smith


1 Answers

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.)

like image 86
mz2 Avatar answered Sep 18 '22 18:09

mz2