【问题标题】:How to handle UITextField position while typing in Xamarin iOS?在 Xamarin iOS 中输入时如何处理 UITextField 位置?
【发布时间】:2017-04-03 22:40:07
【问题描述】:

这是 iOS 移动开发中非常常见的问题,即当您完成 UI 并且它包含太多 UITextFields 时,如果您尝试在 UITextFields 中输入值,这些值会添加到屏幕的中心底部;这些字段隐藏在键盘后面。我们怎样才能摆脱这个普遍的问题?

【问题讨论】:

  • 伙计们,请说明您为什么拒绝投票,以便我可以改进和改进。谢谢。

标签: xamarin xamarin.ios


【解决方案1】:

您可以在 NSNotificationCenter 中使用 AddObserver 方法来判断键盘是否可见和隐藏。

示例代码(仅供参考:去年某个时候从另一篇帖子中获得了以下代码,我不记得该帖子的链接,但它工作正常。)

在 viewdidload 方法中调用 AddObserver

// 键盘弹窗 NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyBoardUpNotification);

// 键盘按下 NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyBoardDownNotification);

如果您有以下方法,您可以在基本控制器库中添加以下方法

 public void KeyBoardUpNotification(NSNotification notification) {
            CGRect keyboardSize = UIKeyboard.BoundsFromNotification(notification);

            // Find what opened the keyboard
            foreach (UIView view in this.View.Subviews) {
                if (view.IsFirstResponder)
                    activeview = view;
            }

            bottom = (activeview.Frame.Y + activeview.Frame.Height + offset);
            scrollamount = (keyboardSize.Height - (View.Frame.Size.Height - bottom));

            if (scrollamount > 0) {
                moveViewUp = true;
                MoveView(moveViewUp);
            } else {
                moveViewUp = false;
            }

        }

     public void KeyBoardDownNotification(NSNotification notification) {
                if (moveViewUp) {
                    MoveView(false);
                }
            }

private void MoveView(bool move) {
            UIView.BeginAnimations(string.Empty, IntPtr.Zero);
            UIView.SetAnimationDuration(0.3);
            CGRect frame = View.Frame;

            if (move) {
                frame.Y -= scrollamount;
            } else {
                frame.Y += scrollamount;
                scrollamount = 0;
            }

            View.Frame = frame;
            UIView.CommitAnimations();
        }

【讨论】:

  • 感谢@megaKertz。我为什么要使用它?虽然我可以用两行代码做到这一点!仅供参考,这不是闲置的方法,它有很多泄漏,打字时结果也出乎意料!
  • @RIYAZ 从来没有说过你应该使用它,如果你认为它可以解决你遇到的问题,你可以使用它。那么你使用的 2 行代码是什么
  • 对不起兄弟,我不是那个意思。我使用它并在这段代码中发现了很多问题,ScrollView 的行为很奇怪,所以我删除了它。
【解决方案2】:

我使用了nuget 包来解决这个问题。我已经覆盖了两个方法并在这些方法中初始化了代码。

下载KeyboardHandler并使用如下:

using KeyboardHandler;


public override void ViewWillAppear(bool animated)
{
  base.ViewWillAppear(animated);
  this.yourScrollView.SubscribeKeyboardManaqger();
}

public override void ViewWillDisappear(bool animated)
{
  base.ViewWillDisappear(animated);
  this.yourScrollView.UnsubscribeKeyboardManaqger();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2022-09-23
    • 2017-03-03
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多