查看这些博文:
https://alexdunn.org/2017/03/21/xamarin-tips-xamarin-forms-ios-custom-tableview-section-titles/
https://alexdunn.org/2017/03/21/xamarin-tips-xamarin-forms-android-custom-tableview-section-titles/
他们描述了使用 TableView 的自定义渲染器来自定义节标题。 iOS 版本:
在共享代码中:
public partial class ColoredTableView : TableView
{
public static BindableProperty GroupHeaderColorProperty = BindableProperty.Create("GroupHeaderColor", typeof(Color), typeof(ColoredTableView), Color.White);
public Color GroupHeaderColor
{
get
{
return (Color)GetValue(GroupHeaderColorProperty);
}
set
{
SetValue(GroupHeaderColorProperty, value);
}
}
public ColoredTableView()
{
InitializeComponent();
}
}
在 iOS 项目中:
[assembly: ExportRenderer(typeof(ColoredTableView),typeof(ColoredTableViewRenderer))]
namespace YOUR_IOS_NAMESPACE
{
public class ColoredTableViewRenderer : TableViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
{
base.OnElementChanged(e);
if (Control == null)
return;
var tableView = Control as UITableView;
var coloredTableView = Element as ColoredTableView;
tableView.WeakDelegate = new CustomHeaderTableModelRenderer(coloredTableView);
}
private class CustomHeaderTableModelRenderer : UnEvenTableViewModelRenderer
{
private readonly ColoredTableView _coloredTableView;
public CustomHeaderTableModelRenderer(TableView model) : base(model)
{
_coloredTableView = model as ColoredTableView;
}
public override UIView GetViewForHeader(UITableView tableView, nint section)
{
return new UILabel()
{
Text = TitleForHeader(tableView, section),
TextColor = _coloredTableView.GroupHeaderColor.ToUIColor(),
TextAlignment = UITextAlignment.Center
};
}
}
}
}
但是我认为使用 ListView 或制作自己的部分(即一个没有为 TableView 设置标题的部分,然后使用单元格可能是最简单的方法。要做到这一点,只需定义一个没有标题的部分并使用 ViewCells对于部分:
<TableView Intent="Data"
HasUnevenRows="true" >
<TableRoot>
<TableSection>
<ViewCell >
<StackLayout Orientation="Horizontal">
<Label x:Name="label1" Text="Section one" />
<Button Text="Button1" Clicked="Handle_Clicked" />
</StackLayout>
</ViewCell>
<TextCell Text="TextCell"
Detail="TextCell Detail" />
<EntryCell Label="Entry Label"
Text="EntryCell Text" />
<SwitchCell Text="SwitchCell Text" />
<ViewCell >
<StackLayout Orientation="Horizontal">
<Label x:Name="label2" Text="Section Two" />
<Button Text="Button2" Clicked="Handle_Clicked" />
</StackLayout>
</ViewCell>
<TextCell Text="TextCell"
Detail="TextCell Detail" />
<EntryCell Label="Entry Label"
Text="EntryCell Text" />
<SwitchCell Text="SwitchCell Text" />
</TableSection>
</TableRoot>
</TableView>