【问题标题】:How can I add these custom cells to a TableView?如何将这些自定义单元格添加到 TableView?
【发布时间】:2018-02-10 12:55:10
【问题描述】:

使用 Xamarin.Forms,如何实现这样的布局?

我说的是灰色背景上的文字提示:

开启个人热点分享...

我可以添加到ListViewTableView 的所有内容都是标准ViewCells,它们都以分隔符和白色背景呈现。

如果使用TableViewListView 无法实现此布局,我如何在标准StackLayout 中呈现ViewCell(如示例图像中的Wi-Fi 密码)?

【问题讨论】:

    标签: ios listview xamarin xamarin.forms


    【解决方案1】:

    即使 TableView 没有开箱即用的 ViewCell 来执行此操作,您当然可以推出自己的实现。显然有一个 TextCell 但它不允许您指定字体大小和其他内容。

    你可以这样做:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DemoTableView.TablePage" Title="TableView">
        <ContentPage.Content>
            <TableView Intent="Settings">
                <TableRoot>
                    <TableSection>
                        <SwitchCell Text="Personal Hotspot" />
                        <ViewCell> <!-- Simple text -->
                            <Label Text="Turn on personal hotspot..." FontSize="Small" ForegroundColor="Gray" />
                        </ViewCell>
                        <ViewCell> <!-- More complex cell -->
                            <StackLayout Orientation="Horizontal>
                                <Image Source="someicon" />
                                <StackLayout>
                                    <Label Text="TO CONNECT USING WIFI" FontSize="Large"/>
                                    <Label Text="Something more" FontSize="Small" />
                                </StackLayout>
                            </StackLayout>
                        </ViewCell>
                    </TableSection>
                </TableRoot>
            </TableView>
        </ContentPage.Content>
    </ContentPage>
    

    这只是一个匆忙编写的简单示例,但您明白了。您还可以通过从 ViewCell 类继承来以编程方式定义自己的单元格并将它们显示在 TableView 中。

    Here's more关于官方文档中的自定义单元格。


    编辑:根据您的评论,我们需要深入研究特定于平台的代码,以禁用对纯文本单元格的选择。您应该使用以下适用于 iOS 的自定义渲染器创建自定义 ViewCell 实现:

    [assembly: ExportCell(typeof(YourCell), typeof(YourCellRenderer))]
    namespace YourProject.iOS
    {
        public class YourCellRenderer : ViewCellRenderer
        {
            public override UITableViewCell GetCell (Cell item, UITableView tv)
            {
                var cell = base.GetCell (item, tv);
                cell.SelectionStyle = UITableViewCellSelectionStyle.None;
                return cell;
            }
        }
    }
    

    【讨论】:

    • 谢谢,但是使用 ViewCell 有两个缺点:a) 我仍然会在点击单元格时获得悬停效果,b) 上面的 SwitchCell 的分隔符会略微缩小,如果有更多的话通常会缩小下面的选项。关于如何克服这些问题的任何想法?
    • @Physikbuddha 哦,对了,没想到。我更新了我的答案。虽然不太确定 b。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多