将子视图添加到 uistackview 不适用于按钮单击

Adding subview to uistackview not working on button click

我正在向 ViewDidLoad 中的堆栈视图添加一堆视图。最后,我添加了一个 "Load More" 按钮,它会重复在 ViewDidLoad 中工作的代码——添加更多已排列的子视图。但是我在屏幕上看不到任何视图。非常感谢任何帮助。

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

这是我基于您的示例代码:

注意事项: 我将堆栈视图设置为:

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

我是 Swift 的新手,但在堆栈视图中添加带有操作的按钮时遇到了类似的问题。

虽然我使用的是 #selector() ,但我认为我的问题是我没有将 @objc 添加到我的按钮变量中。这样,编译器可能无法以某种方式解决目标操作(我不确定)。

请尝试

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

希望对您有所帮助。

谢谢, 阿迪亚