我使用this answer中的代码片段来移除图标之间的间距,它似乎也删除了NavigationBar
中右侧的填充。问题是,在我将页面推入或弹出导航堆栈后,屏幕方向发生变化后,右边的填充再次出现。
为什么自定义渲染器第一次添加自定义视图时会删除此填充?
有没有办法完全删除填充?
更新
如下面的答案所示,删除带有负常数的约束似乎最初起作用,但这些约束在某些时候被放回。
答案 0 :(得分:1)
删除填充的方法是iOS7 +和iOS11之间的区别。
我们可以通过添加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();
}
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;
}
}
}
}
}
}