首页 > 解决方案 > 使用 xamarin.ios c# 以编程方式添加嵌套的堆栈视图

问题描述

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

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

有人可以帮忙吗。

谢谢,桑托什

标签: xamarin.iosmvvmcrossuistackview

解决方案


UIStackView利用 Auto Layout 和 Size Classes 的强大功能来管理水平或垂直的子视图堆栈,这些子视图动态响应 iOS 设备的方向和屏幕大小。您可以通过此文档了解它。

在您的情况下,我们可以构造一个垂直堆栈来放置几个水平堆栈:

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

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


推荐阅读