中心滚动视图对象到每个水平滚动页面 - Xamarin iOS

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

我正在做与此非常相似的事情,https://www.youtube.com/watch?v=EwSTK24IQds, 但是对于每个对象,我都放置了一个 UI 文本字段。当我使用不同的设备滚动浏览每个页面时,文本不会居中显示在屏幕中间。无论设备是什么,我都必须做些什么才能使物体居中? 用户正在填写表单并输入数据,然后滚动到每个字段的下一页。

谢谢

原因:

文本字段在不同设备中的位置取决于文本字段的布局。

解法:

例如,您将文本字段添加到 ViewController 的默认视图。

我在这里提供了两种方法,无论设备是什么,都可以使文本字段在视图中居中:

  • 第一个是使用Frame。你可以计算坐标 不同设备中的文本字段。
  • 第二种是使用Autolayout。你可以给textfield添加约束来 找到它的位置。

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

此外,您还可以在 Storyboard 中添加约束: center a textfield in storyboard