Search code examples
iosxamarinxamarin.iosuiscrollviewxamarin-studio

Centre Scroll View Objects To Each Horizontal Scrolled Page - Xamarin iOS


I am doing something very similar to this, https://www.youtube.com/watch?v=EwSTK24IQds, but for each object, I am placing a UI textfield. When I scroll through each page with different devices, the text does not centre to the middle of the screen. What would I have to do to make the object sit centre no matter what the device is? The user is filling out a form and is typing in data, and scrolling to the next page for each field.

Thanks


Solution

  • Cause:

    The position of your textfield in different devices depending on your textfield's layout.

    Solution:

    For example, you add a textField to the default view of a ViewController.

    I provide two methods here to center a textfield in the view no matter what the device is:

    • The first is use Frame.You can calculate coordinates of the textfield in different device.
    • The second is use Autolayout.You can add constraints to textfield to locate its position.

      public override void ViewDidLoad ()
      {
          base.ViewDidLoad ();
          // Perform any additional setup after loading the view, typically from a nib.
      
          UITextField myTextView = new UITextField();
          Add(myTextView);
      
          float ScreenWidth = (float)UIScreen.MainScreen.Bounds.Width;
          float ScreenHeight = (float)UIScreen.MainScreen.Bounds.Height;
      
          float textFieldWidth = 200;
          float textFieldHeight = 50;
      
          myTextView.Text = "center myTextView";
          myTextView.TextAlignment = UITextAlignment.Center;
          myTextView.BackgroundColor = UIColor.Blue;
      
          //Method One:
          //Frame Center
          //myTextView.Frame = new CGRect(new CGPoint(View.Center.X-textFieldWidth/2,View.Center.Y-textFieldHeight/2), new CGSize(textFieldWidth, textFieldHeight));
      
          //Frame
          //myTextView.Frame = new CGRect(ScreenWidth / 2 - textFieldWidth / 2, ScreenHeight / 2 - textFieldHeight / 2, textFieldWidth, textFieldHeight);
      
          //Method two:
          //autolayout
          //myTextView.TranslatesAutoresizingMaskIntoConstraints = false;
          //View.AddConstraint(NSLayoutConstraint.Create(myTextView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, 1f, textFieldHeight));
          //View.AddConstraint(NSLayoutConstraint.Create(myTextView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, 1f, textFieldWidth));
          //View.AddConstraint(NSLayoutConstraint.Create(myTextView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1f, 10f));
          //View.AddConstraint(NSLayoutConstraint.Create(myTextView, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterY, 1f, 10f));
      
      }
      

    Also,you can add constraints in storyboard: center a textfield in storyboard