Voici ma base de code exemple sur le vôtre:
Notes: Je tournai ma stackview avec:
distribution sur "Remplir l'égalité" et Alignement sur "remplissage"
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
AddViewsInStackView(); // Add views first time in the stackview
AddButtonInStackView(); // Add the "Add button" first time in the stackview
}
private void AddViewsInStackView()
{
// Create 2 views and add them to the stackview
var view1 = new UIView { BackgroundColor = UIColor.Red };
var view2 = new UIView { BackgroundColor = UIColor.Green };
stackView.AddArrangedSubview(view1);
stackView.AddArrangedSubview(view2);
}
private void AddButtonInStackView()
{
// create the "Add button"
var button = new UIButton(UIButtonType.Custom);
button.SetTitle("Add", UIControlState.Normal);
button.SetTitleColor(UIColor.Blue, UIControlState.Normal);
button.TouchUpInside += (sender, e) => AddSupplementaryViews();
stackView.AddArrangedSubview(button); // Add the "Add button" in the stackview
}
private void AddSupplementaryViews()
{
if (stackView.ArrangedSubviews.Any())
{
// Fetch the "Add button" then remove them
var addButton = stackView.ArrangedSubviews.Last();
stackView.RemoveArrangedSubview(addButton); // This remove the view from the stackview
addButton.RemoveFromSuperview(); // This remove the view from the hierarchy
AddViewsInStackView(); // Add new views
AddButtonInStackView(); // Add it again so it will be the last one every time
}
}
Je pense que vous devez créer de nouvelles instances de view1 et view2 dans votre événement de clic sur un bouton. par exemple 'stackView.AddArrangedSubView (new View1());' – Robbie188
view1 et view2 sont déjà dans votre StackView donc ne peuvent pas être ajoutés à nouveau. – Robbie188
Tout d'abord, vérifiez si la vue que vous ajoutez n'est pas nulle. Ensuite, vérifiez après le clic sur le bouton combien de vieww contient votre stackview. Pourriez-vous nous indiquer où vous créez vos instances view1 et view2, s'il vous plaît? – Lapinou