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

时间:2017-02-09 06:49:44

标签: ios user-interface xamarin xamarin.ios ios-keyboard-extension

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

3 个答案:

答案 0 :(得分:4)

答案 1 :(得分:1)

查看示例实施

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

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();
}

答案 2 :(得分:-1)

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