使用 xamarin.ios c# 以编程方式添加嵌套堆栈视图

Adding nested stackviews programmatically using xamarin.ios c#

我正在使用 xamarin 和 mvvmcross 为 android 和 ios 创建一个应用程序。 在 ios 应用程序中,我想添加具有嵌套水平堆栈视图的外部垂直堆栈视图。基本上我只想创建一个基本的人员详细信息屏幕,其中左侧是标签,右侧是文本字段,它们将进入一个水平堆栈视图,并且像这样会有许多水平堆栈视图嵌套在外部垂直堆栈视图中。

我正在互联网上寻找这样的示例,但似乎大多数示例都在 swift 中,但我很难在 c# 中找到一些示例。

有人可以帮忙吗

谢谢, 桑托什

UIStackView 利用自动布局和大小 类 的强大功能来管理水平或垂直的子视图堆栈,动态响应 [=20= 的方向和屏幕大小] 设备。你可以通过这个documentation.

了解一下

对于您的情况,我们可以构建一个垂直堆栈来放置多个水平堆栈:

UIStackView verticalStack = new UIStackView();
View.AddSubview(verticalStack);
verticalStack.Axis = UILayoutConstraintAxis.Vertical;
verticalStack.TranslatesAutoresizingMaskIntoConstraints = false;

// Use auto layout to embed this super vertical stack in the View. Also there's no need to set the height constraint, vertical stack will automatically adjust that depending on its content
verticalStack.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor).Active = true;
verticalStack.TopAnchor.ConstraintEqualTo(TopLayoutGuide.GetBottomAnchor()).Active = true;
verticalStack.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor).Active = true;           

for (int i=0; i<10; i++)
{
    // Here try to put some horizontal stack with Label on left and textfield on right in the father stack.
    UIStackView horizontalStack = new UIStackView();
    horizontalStack.Distribution = UIStackViewDistribution.EqualSpacing;
    horizontalStack.Axis = UILayoutConstraintAxis.Horizontal;
    // UIStackView should use AddArrangedSubview() to add subviews.
    verticalStack.AddArrangedSubview(horizontalStack);
    UILabel textLabel = new UILabel();
    textLabel.Text = "text";
    UITextField textField = new UITextField();
    textField.Placeholder = "enter text";
    horizontalStack.AddArrangedSubview(textLabel);
    horizontalStack.AddArrangedSubview(textField);
}

但是如果每一个横向stack的subView都是几乎相同的样式和布局。为什么不尝试使用 UITableView?您只需要设置单个单元格的内容和布局,然后在 tableView 中使用它。此外,此控件可重复使用且可滚动。