首页 > 解决方案 > 中心滚动视图对象到每个水平滚动页面 - Xamarin iOS

问题描述

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

谢谢

标签: iosxamarinxamarin.iosuiscrollviewxamarin-studio

解决方案


原因:

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

解决方案:

例如,您将 textField 添加到 ViewController 的默认视图。

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

  • 第一个是使用Frame。您可以计算不同设备中文本字段的坐标。
  • 第二个是使用Autolayout。您可以向文本字段添加约束以定位其位置。

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

此外,您可以在情节提要中添加约束:在情节 提要中居中文本字段


推荐阅读