[英]Xamarin iOS custom toolbar renderer inconsistent keyboard height calculation
我正在嘗試為我的 Xamarin 應用程序創建一個工具欄,該工具欄顯示幾個不同的選項,並在使用我的應用程序時位於鍵盤頂部。 在 Android 上,我的工具欄僅通過樣式自動顯示在我的鍵盤頂部。 在 iOS 上,它隱藏在鍵盤后面,所以我決定使用自定義渲染器將其向上推。 我使用從我在這里找到的示例中復制的方法。
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using Foundation;
using CoreGraphics;
using System;
using System.Drawing;
[assembly: ExportRenderer(typeof(ToolBar), typeof(ToolbarRenderer))]
namespace App.Core.XF.Platform.iOS.Renderers
{
internal class ToolbarRenderer : ViewRenderer<ToolBar, UIView>
{
private NSObject _keyboardShowObserver;
private NSObject _keyboardHideObserver;
protected override void OnElementChanged(ElementChangedEventArgs<ToolBar> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
RegisterForKeyboardNotifications();
}
if (e.OldElement != null)
{
UnregisterForKeyboardNotifications();
}
}
private void RegisterForKeyboardNotifications()
{
if (_keyboardShowObserver == null)
{
_keyboardShowObserver = UIKeyboard.Notifications.ObserveWillShow(OnKeyboardShow);
}
if (_keyboardHideObserver == null)
{
_keyboardHideObserver = UIKeyboard.Notifications.ObserveWillHide(OnKeyboardHide);
}
}
private void OnKeyboardShow(object sender, UIKeyboardEventArgs args)
{
NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
CGSize keyboardSize = result.RectangleFValue.Size;
if (Element != null)
{
Element.Margin = new Thickness(0, 0, 0, keyboardSize.Height); //push the entry up to keyboard height when keyboard is activated
}
}
private void OnKeyboardHide(object sender, UIKeyboardEventArgs args)
{
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
}
private void UnregisterForKeyboardNotifications()
{
if (_keyboardShowObserver != null)
{
_keyboardShowObserver.Dispose();
_keyboardShowObserver = null;
}
if (_keyboardHideObserver != null)
{
_keyboardHideObserver.Dispose();
_keyboardHideObserver = null;
}
}
}
}
上面的示例適用於較舊的 iPhone。 但是,在較新的 iPhone 上,它似乎無法正確顯示在鍵盤頂部。 較新的 iPhone 在鍵盤和工具欄之間有一個空白條。 例子:
左邊是 iPhone 8,右邊是 iPhone 13 Pro。
是否有更一致的高度計算適用於舊款和新款 iPhone?
看一下Xamarin.IQKeyboardManager ,用法很簡單。
從 nuget package 安裝后,在 AppDelegate.cs 中初始化插件。
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
IQKeyboardManager.SharedManager.Enable = true; //this line
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
根據我的測試,它在每部 iPhone 上都能正常工作。
PS:不要忘記先刪除自定義渲染器。
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.