如何在 Xamarin.iOS 中显示软件键盘时向上移动布局



我有一个UITextField。当我单击.
时,软键盘覆盖了UITextField。如何向上移动布局,以便我希望它显示在键盘上方.
提前谢谢。

您可以使用 https://github.com/hackiftekhar/IQKeyboardManager

Xamarin iOS 绑定 https://github.com/TheEightBot/Xamarin.IQKeyboardManager

Xamarin Nuget:https://www.nuget.org/packages/Xamarin.IQKeyboardManager/

查看示例暗示

包含文本框的控制器的变量

private UIView activeview;             // Controller that activated the keyboard
private float scroll_amount = 0.0f;    // amount to scroll 
private float bottom = 0.0f;           // bottom point
private float offset = 10.0f;          // extra offset
private bool moveViewUp = false;           // which direction are we moving

ViewDidLoad(( 的键盘观察器。

// Keyboard popup
NSNotificationCenter.DefaultCenter.AddObserver
(UIKeyboard.DidShowNotification,KeyBoardUpNotification);
// Keyboard Down
NSNotificationCenter.DefaultCenter.AddObserver
(UIKeyboard.WillHideNotification,KeyBoardDownNotification);

首先是KeyboardUpNotification方法。 实质上,您计算控件是否将被键盘隐藏,如果是,则计算需要移动多少视图才能显示控件,然后移动它。

private void KeyBoardUpNotification(NSNotification notification)
{
    // get the keyboard size
    RectangleF r = UIKeyboard.BoundsFromNotification (notification);
    // Find what opened the keyboard
    foreach (UIView view in this.View.Subviews) {
        if (view.IsFirstResponder)
            activeview = view;
    }
    // Bottom of the controller = initial position + height + offset      
    bottom = (activeview.Frame.Y + activeview.Frame.Height + offset);
    // Calculate how far we need to scroll
    scroll_amount = (r.Height - (View.Frame.Size.Height - bottom)) ;
    // Perform the scrolling
    if (scroll_amount > 0) {
         moveViewUp = true;
         ScrollTheView (moveViewUp);
    } else {
         moveViewUp = false;
    }
}

键盘关闭事件很简单。 如果视图已被移动,只需将其反转即可。

private void KeyBoardDownNotification(NSNotification notification)
{
    if(moveViewUp){ScrollTheView(false);}
}

滚动视图将以动画方式滚动视图。

private void ScrollTheView(bool move)
{
    // scroll the view up or down
    UIView.BeginAnimations (string.Empty, System.IntPtr.Zero);
    UIView.SetAnimationDuration (0.3);
    RectangleF frame = View.Frame;
    if (move) {
        frame.Y -= scrollamount;
    } else {
        frame.Y += scrollamount;
        scrollamount = 0;
    }
    View.Frame = frame;
    UIView.CommitAnimations();
}

就我而言,我正在使用网格和堆栈,将我的根布局包装在 ScrollView 中,并将方向设置为两者都不是。它无需任何Nuget和代码隐藏即可工作。实际上,我尝试了IQKeyboardManager,但是它都不起作用,依赖项弃用。

最新更新