3

I am using nested UIStackViews in my UITableViewCell. However, when I scroll it is very slow and affects the performance greatly. Is there any way that I can improve performance of nested UIStackViews in UITableViewCell?

This is how I add my stacks to my UITableViewCell:

    let verticalStack = UIStackView()
    verticalStack.axis = .Vertical

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

        let horizontalStack = UIStackView()
        horizontalStack.axis = .Horizontal

        for j in 0..<json["Rows"][i]["Column"].arrayValue.count{
            let label = UILabel()
            label.text = "Test"
            horizontalStack.addArrangedSubview(label)
        }

        verticalStack.addArrangedSubview(horizontalStack)
    }


    cell.addSubview(verticalStack)
fsb
  • 290
  • 10
  • 28
The Cook
  • 1,403
  • 3
  • 17
  • 33
  • how you create cell? try to fill cell asynchronously – Anton Novoselov Aug 03 '16 at 12:16
  • Fill the cell asynchronously? How does it work? – The Cook Aug 03 '16 at 12:58
  • 1
    You might consider "profiling the app". Press and hold on the run button in Xcode to launch the profiler. Choose time profiler, and then record the app to see which lines of code are slow. – JMFR Aug 03 '16 at 14:15
  • Stack views just calculate layout constraints for their arranged subviews, so on their own they shouldn't affect performance. On the other hand if you're running the code above very frequently, you might get slowdowns from that. When does this code execute? How frequently? – Tom Harrington Aug 03 '16 at 20:27

1 Answers1

3

The problem is, that you allocate multiple UILabels while dequeuing. So, everytime you scroll, new labels are created. Usually, you shouldn't do operations with a high performance (like allocations) in the cellForRowAtIndexPath. The better way is to create all labels once and reuse them. If yo have a static number of labels, you can directly add them as arranged subviews in the XIB file (or initially in the cell class), so they will be reused.

Patrick Haaser
  • 353
  • 1
  • 3
  • 10