benin101
benin101

Reputation: 131

Adding subview to uistackview not working on button click

I am adding a bunch of views to a stack view in my ViewDidLoad. At the end I am adding a "Load More" button which would repeat the code that works in the ViewDidLoad - adding more arranged subviews. But I can't see any of the views on the screen. Any help is much appreciated.

public override void ViewDidLoad()
{
  stackView.AddArrangedSubview(view1);
  stackView.AddArrangedSubview.(view2);
  stackView.AddArrangedSubview.(button);
  button.TouchUpInside += (object sender, EventArgs e) =>
  {
    stackView.AddArrangedSubview(view1);
    stackView.AddArrangedSubview.(view2);
}

Upvotes: 0

Views: 4300

Answers (2)

Aditya S
Aditya S

Reputation: 1

I am new to Swift but had encountered a similar problem when adding a button with action in a stackview.

Though I am using a #selector() , I think my problem was that I did not add @objc with my button variable. This way, somehow the target action was not resolved by the compiler probably ( I am not sure).

Please try

@objc lazy var button = new UIButton(UIButtonType.Custom);

Hopefully, it will help.

Thanks, Aditya

Upvotes: 0

Lapinou
Lapinou

Reputation: 1477

Here is my sample code base on yours:

Notes: I set my stackview with :

Distribution set to "Fill equality" and Alignement set to "Fill"

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
    }
}

Upvotes: 4

Related Questions