首页 > 解决方案 > 当标签栏项目超过 5 个并且用户可以重新排序时,如何选择 TabBarController 选定索引?

问题描述

我有一个包含 5 个以上选项卡栏项目的 Xamarin.iOS 应用程序。在这个应用程序的主屏幕中,标签栏是隐藏的。您仍然可以通过视图中的 UIButtons 而不是 Tab Bar 来导航应用程序。

当 tabBar 项目少于 5 个时,我可以通过点击按钮选择索引来轻松导航:

servicesButton.TouchUpInside += (sender, e) =>
    {              
        TabBarController.SelectedIndex = 1;
    };

现在,由于我有超过 5 个选项卡栏项目并且它们可以由用户重新排序,所以我不能使用硬编码索引。

我目前的工作解决方案是这样的:

servicesButton.TouchUpInside += (sender, e) =>
    {
        for (int i = 0; i < TabBarController.ViewControllers.Length; i++)
        {
            if (TabBarController.ViewControllers[i].Title.Equals("Services"))
            {
                TabBarController.SelectedIndex = i;
            }
        }
    };

这似乎可行,但有人知道完成这项任务的更好方法吗?

标签: c#xamarinxamarin.ios

解决方案


You could:

  • Set the Tag property on the view, e.g., services view tag set to 5

  • Use LINQ to select the view controller

  • Then set the SelectedViewController on the TabBarController

Like this:

servicesButton.TouchUpInside += (sender, e) =>
{
    var servicesViewController = TabBarController.ViewControllers.FirstOrDefault(x => x.View.Tag == 5);
    if(servicesViewController != null)
    {
        TabBarController.SelectedViewController = servicesViewController;
    }
};

You can set the tag either in the storyboard/xib or programmatically.


推荐阅读