Как получить высоту клавиатуры на Android и iOS (Xamarin Forms)? - PullRequest
1 голос
/ 12 октября 2019

Я хочу получить высоту Keyboard на Android и iOS (Xamarin Forms).

Когда отображается экран с режимами Portrait и Landscape, какполучить height значение?

Orientations

Я нашел ссылки с Swift на iOS:

Чтовысота экранной клавиатуры iPhone?

Как узнать высоту клавиатуры?

Но можете предоставить мне исходный код на Xamarin

А как получить высоту клавиатуры на Android?

Пожалуйста, помогите мне!

1 Ответ

0 голосов
/ 12 октября 2019

Есть два способа сделать это!

Первый способ : реализовать его для одного UIViewController, если ваше приложение небольшого размера, следующим образом:

Шаг 1: Добавитьполя для отображения и скрытия наблюдателей:

private NSObject _keyboardObserverWillShow;
private NSObject _keyboardObserverWillHide;

Шаг 2. Обновите переопределения ViewDidLoad и ViewDidUnload для добавления / удаления наблюдателей, когда клавиатура отображается или скрыта:

public override void ViewDidLoad() {
    base.ViewDidLoad ();
    _keyboardObserverWillShow = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyboardDidShowNotification);
    _keyboardObserverWillHide = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyboardWillHideNotification);
}

public override void ViewDidUnload() {
    base.ViewDidUnload();
    NSNotificationCenter.DefaultCenter.RemoveObserver(_keyboardObserverWillShow);
    NSNotificationCenter.DefaultCenter.RemoveObserver(_keyboardObserverWillHide);
}

Шаг 3: Затем вы заполняете функции KeyboardDidShowNotification & KeyboardWillHideNotification, которые выполняются для каждого наблюдателя. Это довольно долго и займет у меня некоторое время, чтобы объяснить каждую часть, но вы можете спросить меня в комментариях. Это выглядит следующим образом:

private void KeyboardWillHideNotification (NSNotification notification) 
{
    UIView activeView = View.FindFirstResponder();
    if (activeView == null)
        return;

    UIScrollView scrollView = activeView.FindSuperviewOfType (this.View, typeof(UIScrollView)) as UIScrollView;
    if (scrollView == null)
        return;

    // Reset the content inset of the scrollView and animate using the current keyboard animation duration
    double animationDuration = UIKeyboard.AnimationDurationFromNotification(notification);
    UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, 0.0f, 0.0f);
    UIView.Animate(animationDuration, delegate{
        scrollView.ContentInset = contentInsets;
        scrollView.ScrollIndicatorInsets = contentInsets;
    });
}   

private void KeyboardDidShowNotification (NSNotification notification) 
{
    UIView activeView = View.FindFirstResponder();
    if (activeView == null)
        return;

    ((UITextField)activeView).ShowDoneButtonOnKeyboard();

    UIScrollView scrollView = activeView.FindSuperviewOfType(this.View, typeof(UIScrollView)) as UIScrollView;
    if (scrollView == null)
        return;

    RectangleF keyboardBounds = UIKeyboard.BoundsFromNotification(notification);

    UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, keyboardBounds.Size.Height, 0.0f);
    scrollView.ContentInset = contentInsets;
    scrollView.ScrollIndicatorInsets = contentInsets;

    // If activeField is hidden by keyboard, scroll it so it's visible
    RectangleF viewRectAboveKeyboard = new RectangleF(this.View.Frame.Location, new SizeF(this.View.Frame.Width, this.View.Frame.Size.Height - keyboardBounds.Size.Height));

    RectangleF activeFieldAbsoluteFrame = activeView.Superview.ConvertRectToView(activeView.Frame, this.View);
    // activeFieldAbsoluteFrame is relative to this.View so does not include any scrollView.ContentOffset

    // Check if the activeField will be partially or entirely covered by the keyboard
    if (!viewRectAboveKeyboard.Contains(activeFieldAbsoluteFrame)) {
        // Scroll to the activeField Y position + activeField.Height + current scrollView.ContentOffset.Y - the keyboard Height
        PointF scrollPoint = new PointF(0.0f, activeFieldAbsoluteFrame.Location.Y + activeFieldAbsoluteFrame.Height + scrollView.ContentOffset.Y - viewRectAboveKeyboard.Height);
        scrollView.SetContentOffset(scrollPoint, true);
    }
}

Second Way : создайте обработчик клавиатуры , который можно использовать для каждой страницы с помощью BaseViewController

...