如何在Xamarin iOS中输入时处理UITextField位置?

问题描述:

它在iOS移动开发中非常常见的问题是,当你完成你的UI并且它包含太多的UITextField时,如果你尝试在UITextFields中输入值,那么它们被添加到屏幕的中心底部;这些字段隐藏在键盘后面。我们如何摆脱这个普遍问题?如何在Xamarin iOS中输入时处理UITextField位置?

+0

伙计们,请提到你为什么反对投票吧,这样我可以改进,在这项工作。谢谢。 – RIYAZ

我已经使用了一个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(); 
} 

enter image description here

你可以使用键盘时是可见的和隐藏在NSNotificationCenter的方法的addObserver。

示例代码(FYI:得到了另一篇文章下面的代码的某个时候,去年,我不记得链接到职位,但它工作正常)

调用的addObserver在viewDidLoad方法

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

// Keyboard Down 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(); 
     } 
+0

感谢@megaKertz。我为什么要使用它?虽然我可以在两行代码中完成! 仅供参考这不是闲置的方法,它有很多的泄漏和结果也意想不到,而打字! – RIYAZ

+0

@RIYAZ永远不要说你应该使用它,你可以,如果你认为它解决了你的问题。那么你使用的两行代码是什么 – megaKertz

+0

对不起,我不是那个意思。我用它在这段代码中发现了很多问题,ScrollView的表现很奇怪,所以我删除了它。 – RIYAZ