如何在iOS上的Xamarin.Forms的NavigationBar中删除重新出现的填充?

时间:2018-01-31 12:26:46

标签: xamarin.forms xamarin.ios

我使用this answer中的代码片段来移除图标之间的间距,它似乎也删除了NavigationBar中右侧的填充。问题是,在我将页面推入或弹出导航堆栈后,屏幕方向发生变化后,右边的填充再次出现。

为什么自定义渲染器第一次添加自定义视图时会删除此填充?

有没有办法完全删除填充?

enter image description here

enter image description here

更新

如下面的答案所示,删除带有负常数的约束似乎最初起作用,但这些约束在某些时候被放回。

enter image description here

1 个答案:

答案 0 :(得分:1)

删除填充的方法是iOS7 +和iOS11之间的区别。

在iOS7 +上:

我们可以通过添加UIBarButtonSystemItem.FixedSpace来删除它:

public override void ViewWillAppear(bool animated)
{
    base.ViewWillAppear(animated);

    var navigationItem = this.NavigationController.TopViewController.NavigationItem;

    List<UIBarButtonItem> list = new List<UIBarButtonItem>();
    foreach (var rightItem in navigationItem.RightBarButtonItems)
    {
        var button = new UIButton(new CGRect(0, 0, 32, 32));
        button.SetImage(rightItem.Image, UIControlState.Normal);

        FieldInfo fi = rightItem.GetType().GetField("clicked", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
        Delegate del = (Delegate)fi.GetValue(rightItem);
        button.TouchUpInside += (EventHandler)del;

        UIBarButtonItem item = new UIBarButtonItem(button);
        list.Add(item);
    }

    if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
    {
        UIBarButtonItem negativeSpacer = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace);
        negativeSpacer.Width = -16;
        list.Insert(0, negativeSpacer);
    }

    this.NavigationController.TopViewController.NavigationItem.RightBarButtonItems = list.ToArray();
}

在iOS 11上:

iOS11上的navigationBar有一些区别,所以我们可以通过修改方法ViewDidLayoutSubviews()ViewWillAppear()中的内容来实现这一点:

public override void ViewDidLayoutSubviews()
{
    base.ViewDidLayoutSubviews();

    tryToRelayout();
}

public override void ViewWillAppear(bool animated)
{
    base.ViewWillAppear(animated);
    ... ...//code above

    tryToRelayout();
}

void tryToRelayout()
{
    if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
    {
        UINavigationItem item = NavigationController.TopViewController.NavigationItem;
        var array = item.RightBarButtonItems;
        if (array != null)
        {
            UIBarButtonItem buttonItem = array[0];
            if (buttonItem.CustomView.Superview != null)
            {
                UIView view = buttonItem.CustomView.Superview.Superview.Superview;
                var arrayConstraint = view.Constraints;
                foreach (NSLayoutConstraint constant in arrayConstraint)
                {
                    if (constant.Constant < 0)
                    {
                        constant.Constant = 0;
                    }
                }
            }
        }
    }
}