title: Swift: UITableView increments layoutSubviews() when scrolling
body: <p>I have a table view with custom cell in Swift that contains a horizontal layout UIView. I have noticed that when scrolling the correctly positioned subview in the horizontal view starts to multiply. I guess this has something to do with layoutSubviews() being called when table scrolls and the fact tableview recycles its cells when hidden and shows them when needed, but ignores currently positioned subviews..</p>
  
  <p>It looks something like this</p>
  
  <p><img src="https://i.stack.imgur.com/OVxS1.gif" alt="enter image description here"></p>
  
  <p>There's already a similar question from before, but it has no good answer.</p>
  
  <p><a href="https://stackoverflow.com/questions/2815887/uiscrollview-calling-superviews-layoutsubviews-when-scrolling">UIScrollview calling superviews layoutSubviews when scrolling?</a></p>
  
  <p>Here's the code I'm using inside my custom cell for horizontal positioning:</p>
  
  <pre><code>class HorizontalLayout: UIView {
  
      var xOffsets: [CGFloat] = []
  
      override func layoutSubviews() {
  
          var width: CGFloat = 0
  
          for i in 0..&lt;subviews.count {
              var view = subviews[i] as UIView
              view.layoutSubviews()
              width += xOffsets[i]
              view.frame.origin.x = width
              width += view.frame.width
          }
          self.frame.size.width = width
  
      }
  
      override func addSubview(view: UIView) {
          xOffsets.append(view.frame.origin.x)
          super.addSubview(view)
      }
  
      func removeAll() {
          for view in subviews {
              view.removeFromSuperview()
          }
          xOffsets.removeAll(keepCapacity: false)
      }
  
  }
  </code></pre>
  
  <p>Taken from here: <a href="https://medium.com/swift-programming/dynamic-layouts-in-swift-b56cf8049b08" rel="nofollow noreferrer">https://medium.com/swift-programming/dynamic-layouts-in-swift-b56cf8049b08</a></p>
  
  <p>Using inside custom cell like so:</p>
  
  <pre><code>func loadStops(stops:[String]) {
      for stop in stops {
          // just testing purposes only
          let view = UIView(frame: CGRectMake(10, 0, 40, 40)) 
          view.backgroundColor = UIColor.redColor()
          stopsView.addSubview(view)
      }
  }
  </code></pre>
  
  <p>Is there a way to fix this problem and prevent the subview of being multiplied when scrolling and perhaps a better way to position subviews horizontally in a tableview cell?</p>