As I run your code test, I think the problem occurs when your cellStackView
is in safe area. Add this line of code to in your for loop to fix the issue:
cellStackView.insetsLayoutMarginsFromSafeArea = false
Default of insetsLayoutMarginsFromSafeArea is true
so UIKit will add aditional value for any margins are in safe area.