1

I'm trying to create a table editor with buttons to add or remove rows and columns and I'm having an issue with the remove part.

I start with a 2*2 table, made of 2 vertical stacks in a horizontal stack, filled with label A and C in the first vStack and B andD in the second vStack . My button is supposed to remove the last item in every vertical stack, so that it removes the last row on screen. It seems to be working in a way, the last row kind of disappear but the labels which were inside suddenly overlap with the first row on the screen.

Here is my code, and a screen capture of the overlapping issue :

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var horizontalStack: UIStackView!
    
    @IBAction func removeRow(_ sender: Any) {
        for vStack in horizontalStack.arrangedSubviews {
            if let stack = vStack as? UIStackView {
                var index = stack.arrangedSubviews.count
                index -= 1
                print(stack.arrangedSubviews)
                stack.removeArrangedSubview(stack.arrangedSubviews[index])
                print(stack.arrangedSubviews)
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
    }
}

(I'm still learning about down casting so it might not be the best way to achieve what I want, however I don't think it's the cause of my issue (or is it ?).)

before clicking button after clicking button

When I print the content of my stack before and after having removed the last item, it's indeed disappeared so I'm guessing the issue is more likely to be coming from the screen itself not properly updating, or constraints causing issues, I don't know.

If you have any idea, I would be glad to hear it.

Prunsse
  • 51
  • 6

1 Answers1

1

From iOS 12.0 and above you should use

stackView.arrangedSubviews[index].removeFromSuperview()

If you use removeArrangedSubview(), there is a bug where the view at the specified index removed, but still appears at CGPoint(x: 0, y: 0).

Check for more details UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview?

kerim.ba
  • 276
  • 1
  • 8
  • Is there a way to reload the stackview once removeFromSuperview has been called so that we see the change right away? – Luke Irvin Apr 06 '23 at 19:36