2017-08-30 122 views
0

我在我的ViewDidLoad中添加了一堆视图到堆栈视图。最后,我添加一个“加载更多”按钮,它将重复在ViewDidLoad中工作的代码 - 添加更多排列的子视图。但是我看不到屏幕上的任何视图。任何帮助深表感谢。添加子视图到uistackview没有按钮点击工作

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

我认为你需要创建新的实例您的按钮点击事件中的view1和view2。例如'stackView.AddArrangedSubView(new View1());' – Robbie188

+1

view1和view2已经在您的StackView中,因此不能再次添加。 – Robbie188

+0

首先,检查您添加的视图是否为空。其次,点击按钮后检查你的堆栈视图包含多少个vieww。您能否向我们提供您创建view1和view2实例的位置? – Lapinou

回答

0

这里是你的我的示例代码库:

注:设置我stackview有:

分配设置为 “填充平等” 和Alignement设置为 “填充”

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

这几乎是我想要做的。视图也被添加到堆栈视图中。它只是没有立即在屏幕上更新。当我移动到另一个视图,然后回到这个视图时,我可以看到添加的子视图。所以我猜我需要做一些事情来添加子视图后刷新视图。 – benin101

+0

您能否请您提供您的代码,在堆栈视图中添加视图的位置?另外:你确定你不是从后台线程添加这些视图? – Lapinou