有没有办法在Xamarin.Forms中减少导航栏上两个图标之间的间距?
有关问题,请参阅下图:
这个距离适用于2个图标,但是当使用3时,它会占据导航栏的一半 - 这可以减少任何方式吗?
提前致谢。
答案 0 :(得分:4)
您可以通过创建NavigationRenderer或PageRenderer两种方式来完成。您必须重新创建UIButtons以替换每个工具栏项,并从委托中获取Xamarin.Forms项中的图像。当您将CGREct设置为UIButton时,您可以在此处调整高度和宽度属性。
这是我使用PageRenderer的实现。
[assembly: Xamarin.Forms.ExportRenderer(typeof(Xamarin.Forms.ContentPage), typeof(ContentPageRenderer))]
public class ContentPageRenderer : PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var navigationItem = this.NavigationController.TopViewController.NavigationItem;
foreach (var rightItem in navigationItem.RightBarButtonItems)
{
var button = new UIButton(new CGRect(0, 0, 50, 50));
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;
rightItem.CustomView = button;
}
}
}
注意:如果您动态更改Xamarin.Forms页面中的工具栏项,它将覆盖渲染更改。
希望这有帮助。
答案 1 :(得分:0)
有一种简单的方法可以获得您想要的效果,请查看我的示例代码:
public class MainViewController : UIViewController
{
public MainViewController ()
{
this.View.Frame = UIScreen.MainScreen.Bounds;
this.View.BackgroundColor = UIColor.Red;
UIImage image1 = UIImage.FromFile ("test1.png");
UIImage image2 = UIImage.FromFile ("test2.png");
//The regular way to set right bar items
// UIBarButtonItem barBtn1 = new UIBarButtonItem (image1, UIBarButtonItemStyle.Done, null);
// UIBarButtonItem barBtn2 = new UIBarButtonItem (image2, UIBarButtonItemStyle.Done, null);
// this.NavigationItem.SetRightBarButtonItems (new UIBarButtonItem[]{ barBtn1, barBtn2 }, true);
//Use CustomView with two UIButton as a right bar item
int btnLength = 35;
UIButton btn1 = new UIButton ();
btn1.Frame = new CGRect (0, 0, btnLength, btnLength);
btn1.SetImage (image1, UIControlState.Normal);
btn1.TouchUpInside += delegate {
Console.WriteLine("btn1 clicked.");
};
UIButton btn2 = new UIButton ();
btn2.Frame = new CGRect (10+btnLength, 0, btnLength, btnLength);
btn2.SetImage (image2, UIControlState.Normal);
btn2.TouchUpInside += delegate {
Console.WriteLine("btn2 clicked.");
};
UIView toolbar = new UIView (new CGRect (0, 0, 10+2*btnLength, btnLength));
toolbar.BackgroundColor = UIColor.White;
toolbar.AddSubview (btn1);
toolbar.AddSubview (btn2);
this.NavigationItem.SetRightBarButtonItem (new UIBarButtonItem (toolbar),true);
}
}
这是2种不同方式的截图,常规风格:
CustomView样式:
如果您仍有问题,请将其保留在此处,我会对其进行检查。
希望它可以帮到你。