在UIScrollView中以编程方式在Xamarin IOS中添加一些UITextView和其他元素

在UIScrollView中以编程方式在Xamarin IOS中添加一些UITextView和其他元素,ios,iphone,uiscrollview,xamarin.ios,uitextview,Ios,Iphone,Uiscrollview,Xamarin.ios,Uitextview,由于我是Xamarin IOS的初学者,我需要您的回答或建议,以便在UIScrollView中添加一些元素 我有一个ViewController,它包含一个UIImageView,然后是一些UILabel和两个或多个UITextView。由于文本很长,我必须添加一个用于滚动ViewController的UIScrollView。因此,我编写了以下代码: public class PostViewController : UIViewController { UIScrol

由于我是Xamarin IOS的初学者,我需要您的回答或建议,以便在UIScrollView中添加一些元素

我有一个ViewController,它包含一个UIImageView,然后是一些UILabel和两个或多个UITextView。由于文本很长,我必须添加一个用于滚动ViewController的UIScrollView。因此,我编写了以下代码:

public class PostViewController : UIViewController
    {
        UIScrollView scrollView;

        private UIImageView _postHeaderImage;

        private UILabel _postTopTag;
        private UILabel _postTitle;

        private UILabel _sourceAndpublicationDate;

        private UITextView _postSummary;
        private UITextView _postText;

        private UIImage image;

        public PostViewController()
        {
            View.BackgroundColor = UIColor.White;
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();



            // ScrollView
            scrollView = new UIScrollView();

            image = UIImage.FromFile("Article1.jpg");
            _postHeaderImage = new UIImageView(UIImage.FromBundle("Article1.jpg"));


            _postTopTag = InitUILabel("Santé", fontSize: 12, color: Colors.TextGrayColor, alignment: UITextAlignment.Left, bold: true);
            _postTopTag.AttributedText = new NSAttributedString("Santé", underlineStyle: NSUnderlineStyle.Single);

            _postTitle = InitUILabel("Alaska - Une «éponge miracle» contre le cancer ", fontSize: 26, bold: true, alignment: UITextAlignment.Left);


            _sourceAndpublicationDate = InitUILabel("www.letelegramme.fr" + " - " + "Depuis 23 Heure(s)", fontSize: 13, alignment: UITextAlignment.Left);

            _postSummary = new UITextView();
            _postSummary.Editable = false;
            _postSummary.ScrollEnabled = false;
            _postSummary.Text = "La « Latrunculia austini » vit à une profondeur variant de 70 à 220 m, dans des zones difficiles d'accès.";



            image = UIImage.FromFile("Article1.jpg");
            _postHeaderImage = new UIImageView(UIImage.FromBundle("Article1.jpg"));


            _postText = new UITextView();
            _postText.Editable = false;
            _postText.ScrollEnabled = false;
            _postText.Text = @"«La molécule la plus active contre le cancer du pancréas».
Des chercheurs ont découvert, en Alaska (États-Unis), qu'une petite éponge des profondeurs possède une composition chimique capable de traiter cette tumeur parmi les plus agressives.
Une petite éponge verte, découverte dans les eaux glacées et sombres au large de l'Alaska, pourrait offrir la première arme efficace contre le cancer du pancréas, une tumeur agressive face à laquelle la médecine a peu de recours.

« Personne ne regarde cette éponge en se disant c'est une éponge miracle, mais elle pourrait l'être », s'exclame Bob Stone, chercheur au Centre scientifique de la pêche d'Alaska de l'Agence américaine océanique et atmosphérique (NOAA). Il a été le premier à découvrir cette éponge de la taille d'une balle de golfe, baptisée « Latrunculia austini », en 2005, lors d'une expédition d'exploration des écosystèmes sous-marins.

Des tests en laboratoire ont révélé que plusieurs de ses molécules détruisent sélectivement les cellules cancéreuses pancréatiques, a indiqué Mark Hamann, un chercheur de la faculté de médecine de l'Université de Caroline du Sud, en collaboration avec Fred Valeriote, de l'Institut Henry Ford du cancer, à Detroit. « C'est sans aucun doute la molécule la plus active contre le cancer du pancréas que nous voyons », se réjouit Mark Hamman.";

            scrollView.AddSubviews(_postHeaderImage, _postTopTag, _postTitle, _sourceAndpublicationDate, _postSummary, _postText);

            View.AddSubview(scrollView);
        }

        public override void ViewDidLayoutSubviews()
        {
            var frameWidth = View.Frame.Width ;

            scrollView.Frame = new CoreGraphics.CGRect(0, 0, this.View.Bounds.Size.Width, 5000);
            scrollView.ContentSize = scrollView.Frame.Size; // This may not be what you actually want, but what you had before was certainly wrong.

            _postHeaderImage.Frame = new CoreGraphics.CGRect(0, 0, View.Frame.Width, (View.Frame.Width * image.Size.Height / image.Size.Width));

            float width = (float)(View.Frame.Size.Width - 40);




            _postTopTag.Frame = new CGRect(10, _postHeaderImage.Frame.Size.Height, frameWidth, 20);

            _postTitle.Frame = new CGRect(10, _postTopTag.Frame.Y + _postTopTag.Frame.Size.Height, frameWidth, 80);

            _sourceAndpublicationDate.Frame = new CGRect(10,_postTitle.Frame.Y + _postTitle.Frame.Size.Height, frameWidth, 20);


            SizeF size = (SizeF)((NSString)_postSummary.Text).StringSize(_postSummary.Font, constrainedToSize: new SizeF(width, (float)View.Frame.Size.Height),
                    lineBreakMode: UILineBreakMode.WordWrap);
            _postSummary.Frame = new CGRect(10, _sourceAndpublicationDate.Frame.Y + _sourceAndpublicationDate.Frame.Size.Height, size.Width, size.Height);


            size = (SizeF)((NSString)_postText.Text).StringSize(_postText.Font, constrainedToSize: new SizeF(width, (float)View.Frame.Size.Height),
                    lineBreakMode: UILineBreakMode.WordWrap);

            _postText.Frame = new CGRect(10, _postSummary.Frame.Y + _postSummary.Frame.Size.Height, size.Width, size.Height);


        }


        public static UILabel InitUILabel(string text, int? color = null, UITextAlignment? alignment = null, nfloat? fontSize = null, bool? bold = false)
        {
            UILabel _label = new UILabel();
            _label.Text = text;
            _label.TextColor = Colors.FromHex(color == null ? Colors.MainColor : color.Value);
            _label.TextAlignment = (alignment == null ? UITextAlignment.Center : alignment.Value);
            _label.LineBreakMode = UILineBreakMode.WordWrap;
            _label.Lines = 0;
            if (fontSize != null && !bold.Value)
                _label.Font = UIFont.SystemFontOfSize(fontSize.Value);
            else if (fontSize != null && bold.Value)
                _label.Font = UIFont.BoldSystemFontOfSize(fontSize.Value);
            else if (bold.Value)
                _label.Font = UIFont.BoldSystemFontOfSize(14f);

            return _label;

        }

    }
如果运行此控制器,您将看到我在UIScrollView的大小以及UITextView的大小方面有很多问题

在你看来,我用了一个很好的方法来显示我的控制器,还是你有其他方法来推荐我

*我在模拟器中使用ios10

谢谢

编辑:

我用过Cirrius,但没用! 代码如下:

public override void ViewDidLayoutSubviews()
        {
            base.ViewDidLayoutSubviews ();
            View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints ();

            View.AddConstraints (

                scrollView.AtTopOf (View, 50),
                scrollView.WithSameWidth (View)
            );

            scrollView.AddConstraints (
                _postTopTag.Below (_postHeaderImage, 15),
                _postTopTag.AtLeftOf (View, 10),
                _postTopTag.WithSameWidth (View).Minus (40)
                //...
            );
        }

这可以通过使用AutoLayout约束作为最佳方法来实现,但如果使用代码隐藏来实现这一点,也可以通过设置scrollview的适当高度和宽度以及设置ContentSize来实现

scrollview的高度和宽度应与您案例中的父视图相同

ContentSize应该根据您在scrollview中的实际内容。 例如,ContentSize高度参数需要设置为scrollview内部内容的总高度

ContentSize宽度参数将与scrollview宽度相同

还要确保将scrollview的bounce verticall属性设置为true


在代码中,您似乎以错误的方式设置了Scrollview大小和ContentSize

在解释之前,我认为您需要了解UIScrollview上的
Frame
ConentSize
之间的区别

  • 框架:要在屏幕上显示的区域

  • ContentSize:可以滚动查看的区域

关于
框架的解决方案
自动布局
  • 框架 首先设置框架

    scrollView.Frame = new CGRect(0, 0, this.View.Bounds.Size.Width, this.View.Bounds.Size.Height);
    
    设置所有控件后设置contentSize(根据最后一个控件计算高度)

  • 自动布局 这是一个复杂的过程

    关于如何在UIScrollview上自动布局,请参阅我最近的文章和

    官方API:

    自动布局的简单方法:


直接设置帧不是最佳做法。您应该创建自动布局约束。我使用了cirrial.FluentLayouts.Touch,但它没有显示我的元素。非常感谢。这正是我想要的。正如我所说的,我是初学者,非常感谢你的解释。谢谢你的回答,夏科尔给出了同样的答案,但更完整。
_postText.Frame = new CGRect(10, _postSummary.Frame.Y + _postSummary.Frame.Size.Height, size.Width, size.Height);
//insert here ,at the end of method ViewDidLayoutSubviews
scrollView.ContentSize = new CGSize(View.Frame.Width, _postText.Frame.Y + _postText.Frame.Height);