我的iOS本机代码中为主页有一个自定义渲染器。当应用启动时,它可以完美运行,并使用我想要的iOS系统图标呈现Navbar项目。但是,如果我离开主页导航,当我向后导航RightBarButtonItems
数组仅包含两个未实例化的对象时,我将插入一个检查(RightNavItems.Title == null
)以在这种情况下继续查看如果我离开并再次返回,由于RightBarButtonItems
数组现在为空,则将崩溃,并且确实会渲染这些项目。
为什么导航回主页时工具栏项未初始化?在这样的自定义渲染器中处理导航的正确方法是什么?
以下是自定义渲染器的代码:
public class ItemsPageRenderer : PageRenderer
{
public new ItemsPage Element
{
get { return (ItemsPage)base.Element; }
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var rightNavList = new List<UIBarButtonItem>();
var navigationItem = this.NavigationController.TopViewController.NavigationItem;
for (var i = 0; i < Element.ToolbarItems.Count; i++)
{
var reorder = (Element.ToolbarItems.Count - 1);
var ItemPriority = Element.ToolbarItems[reorder - i].Priority;
UIBarButtonItem RightNavItems = navigationItem.RightBarButtonItems[i];
if (RightNavItems.Title == null)
continue;
if (RightNavItems.Title.ToLower() == "add")
{
rightNavList.Add(new UIBarButtonItem(UIBarButtonSystemItem.Add)
{
Action = RightNavItems.Action,
Target = RightNavItems.Target
});
}
else if (RightNavItems.Title.ToLower() == "edit")
{
rightNavList.Add(new UIBarButtonItem(UIBarButtonSystemItem.Edit)
{
Action = RightNavItems.Action,
Target = RightNavItems.Target
});
}
else
{
rightNavList.Add(RightNavItems);
}
}
navigationItem.SetRightBarButtonItems(rightNavList.ToArray(), false);
}
}
答案 0 :(得分:1)
检查此代码段
var rightNavList = new List<UIBarButtonItem>();
var navigationItem = this.NavigationController.TopViewController.NavigationItem;
for (var i = 0; i < Element.ToolbarItems.Count; i++)
{
var reorder = (Element.ToolbarItems.Count - 1);
var ItemPriority = Element.ToolbarItems[reorder - i].Priority;
UIBarButtonItem RightNavItems = navigationItem.RightBarButtonItems[i];
if (RightNavItems.Title == null)
continue;
if (RightNavItems.Title.ToLower() == "add")
{
rightNavList.Add(new UIBarButtonItem(UIBarButtonSystemItem.Add)
{
Action = RightNavItems.Action,
Target = RightNavItems.Target
});
}
else if (RightNavItems.Title.ToLower() == "edit")
{
rightNavList.Add(new UIBarButtonItem(UIBarButtonSystemItem.Edit)
{
Action = RightNavItems.Action,
Target = RightNavItems.Target
});
}
else
{
rightNavList.Add(RightNavItems);
}
}
navigationItem.SetRightBarButtonItems(rightNavList.ToArray(), false);
第一次进入页面时,您将项目外观从title
更改为icon
,但是,当第二次进入页面时,条件RightNavItems.Title == null
为true,因此它跳出了循环而不向列表中添加任何项目,因此navigationItem.SetRightBarButtonItems
最后添加一个空数组。
修改如下
if (RightNavItems.Title == null)
{
rightNavList.Add(RightNavItems); //add this line.
continue;
}