在UIScrollView中以编程方式添加一些UITextView和其他元素Xamarin IOS [英] add some UITextView s and other elements in UIScrollView programmatically Xamarin IOS

查看:75
本文介绍了在UIScrollView中以编程方式添加一些UITextView和其他元素Xamarin IOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我有一个ViewController,它包含一个UIImageView,然后是一些UILabel和两个或多个UITextView。由于文本很长,我要添加一个UIScrollView来滚动ViewController。所以,我写了这段代码:

  public class PostViewController:UIViewController 
{
UIScrollView scrollView;

private UIImageView _postHeaderImage;

私人UILabel _postTopTag;
private UILabel _postTitle;

私人UILabel _sourceAndpublicationDate;

private UITextView _postSummary;
private UITextView _postText;

私人UIImage图片;

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,颜色:Colors.TextGrayColor,alignment:UITextAlignment.Left,bold:true);
_postTopTag.AttributedText = new NSAttributedString(Santé,underlineStyle:NSUnderlineStyle.Single);

_postTitle = InitUILabel(Alaska - Une«épongemiracle»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àuneprofondeur variant de70à220m,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 = @«Lamoléculelaplus active contre le cancerdupancréas»。
Des chercheursontdécouvert,en Alaska(États-Unis),qu'unepetiteépongedesprofondeurspossèdeunecomposition
Unepetiteépongeverte,découvertedansleseauxglacéessetsombres au large de l'Alaska,pourrait offrirlapremièrearmeefficace contre le cancerdupancréas,une tumeur agressive face àlaquelle拉MEDECINE一个PEU德recours

«Personne NE regarde CETTEépongeEN SE disant花莲UNEéponge奇迹,MAIS ELLE pourrait L'理由»,s'exclame鲍勃·斯通,chercheur AU中心阿拉斯加州和阿拉斯加州民族解放运动(NOAA),阿尔卑斯山,阿尔卑斯山,巴黎,巴黎,海滩,巴黎,海滩,海滩,海滩,海滩,海滩,海滩,海滩,海滩无国界医学组织探索性研究marins。

Des tests en laboratoireontrévéléqueplusieurs desesmoléculesdétruisentélectivementlescellulescancéreusespancréatiques,indiquéMarkHamann,un chercheur delafacultédemédecinedel'UniversolineéCarolinedu Sud,en合作avec Fred Valeriote,de l'Institut Henry Ford du cancer,àDetroit。 «C'est sans aucun doutelamoléculelaplus active contre le cancerdupancréasquenous voyons»,seréjouitMarkHamman。;

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; //这可能不是你真正想要的,但你之前所拥有的肯定是错的。

_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大小=(的SizeF)((的NSString)_postSummary.Text).StringSize(_postSummary.Font,constrainedToSize:新的SizeF(宽度,(浮点)View.Frame.Size.Height ),
lineBreakMode:UILineBreakMode.WordWrap);
_postSummary.Frame = new CGRect(10,_sourceAndpublicationDate.Frame.Y + _sourceAndpublicationDate.Frame.Size.Height,size.Width,size.Height);


大小=(的SizeF)((的NSString)_postText.Text).StringSize(_postText.Font,constrainedToSize:新的SizeF(宽度,(浮点)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);

返回_label;

}

}

如果你跑这个控制器,你会看到我有很多UIScrollView的大小问题,也有我的UITextView的大小。



在你看来,我用一种很好的方法来显示我的控制器,或者你有另一种方式来推荐我?



*我在模拟器中使用IOS 10



谢谢



编辑:



我使用过Cirrious但它不起作用!
以下是代码:

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


解决方案

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




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


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




解决方案框架 AutoLayout




  • 框架



    首先设置框架。

      scrollView.Frame = new CGRect(0,0,this.View.Bounds.Size.Width,this.View.Bounds .Size.Height); 

    设置所有控件后设置contentSize(根据最后一个控件计算高度)



    'pre> _postText.Frame =新的CGRect(10,_postSummary.Frame.Y + _postSummary.Frame.Size.Height,size.Width,size.Height) ;
    //插入这里,在方法ViewDidLayoutSubviews
    scrollView.ContentSize =新CGSize(View.Frame.Width,_postText.Frame.Y + _postText.Frame.Height)的端部;


  • AutoLayout



    它是方式复杂。



    关于如何在UIScrollview上自动布局,请参阅我最近的帖子此处这里



    官方API:程序化布局约束



    简单方法使用AutoLayout: Cirrious.FluentLayout



    使用Cir的UIScrollView中的Autolayouts rious.FluentLayouts.Touch



As I'm beginner in Xamarin IOS, I need your answer or suggestion for adding some elements in UIScrollView.

I've a ViewController which contains one UIImageView then some UILabel and two or more UITextView. As the texts are long, I've to add a UIScrollView for scrolling the ViewController. So, I've written this code:

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;

        }

    }

If you run this controller, you will see that I have lots of problem with size of UIScrollView and also with size of my UITextView s.

In your mind, I am used a good method for displaying my controller or you have another way to propose me ?

*I use IOS 10 in simulator

Thanks

EDIT:

I've used Cirrious but it doesn't worked! Here is the code:

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

解决方案

Before the explaination, I think you need to understand the difference between Frame and ConentSize on UIScrollview.

  • Frame : The area you want to display on the screen.

  • ContentSize: The area which can scroll to see.

Solution on Frame and AutoLayout

  • Frame

    Set frame at first.

    scrollView.Frame = new CGRect(0, 0, this.View.Bounds.Size.Width, this.View.Bounds.Size.Height);
    

    Set contentSize after setting all the control(calcuate height according to the last control )

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

  • AutoLayout

    It is complex in the way.

    About how to autolayout on UIScrollview , refer to my recent post here and here

    Official API : Programmatic Layout Constraints

    Simple Way with AutoLayout : Cirrious.FluentLayout

    Autolayouts in UIScrollView using Cirrious.FluentLayouts.Touch

这篇关于在UIScrollView中以编程方式添加一些UITextView和其他元素Xamarin IOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆