Search code examples
iosxamarin.ios

ScrollView doesn't appear on ViewContooller


This is my first foray into using anchors with my constraints on the ViewController and it no doubt has issues. Right now I able to compile and run the project with no errors and the viewcontroller appears with everything except the scrollview which (should) contains the subviews I need.

I've implemented a system of user defined data elements and have developed a screen in Android to capture the data and now I need to do the same for the iOS version of the app. This is my code thus far:

public string action;
public string emplyoyeeid;
public nfloat imageHeight = 0;
public nfloat imageWidth = 0;
public byte[] imageBytes;

DataSet dsAdditionalData = new DataSet();
DataInterfaceWeb.DataInterface myService = new DataInterfaceWeb.DataInterface();
public AdditionalData (IntPtr handle) : base (handle)
    {
    }
public override void ViewDidLoad()
{
    var NavBarHeight = UIApplication.SharedApplication.StatusBarFrame.Size.Height +
                           (NavigationController?.NavigationBar.Frame.Height ?? 0.0);
    nfloat height = View.Bounds.Height;
    nfloat width = View.Bounds.Width;
    float padding = 10.0f;
    int n = 20;
    float h = 50.0f;
    float w = 50.0f;
    UIImageView banner = new UIImageView();
    UIImageView employeeimage = new UIImageView();
    employeeimage.Frame = new RectangleF(0f, 0f, (float)imageWidth, (float)imageHeight); 
    UIImage Mybitmap = Utils.GetImagefromByteArray(imageBytes);
    employeeimage.Image = Mybitmap;
    UIButton btnSave = new UIButton();
    btnSave.SetTitle("Save", UIControlState.Normal);
    btnSave.SetTitleColor(UIColor.Black, UIControlState.Normal);
    btnSave.BackgroundColor = UIKit.UIColor.FromRGB(255, 215, 0);
    btnSave.HorizontalAlignment = UIControlContentHorizontalAlignment.Left;
    btnSave.Layer.BorderWidth = 1;
    btnSave.Frame = new CGRect(0, 0f, 75f, 26);
    UILabel lblAgeAsOf = new UILabel();
    lblAgeAsOf.Text = "Age as of: ";
    List<UILabel> labellist = new List<UILabel>();
    List<UITextField> fieldlist = new List<UITextField>();
    UIView line = new UIView();
    line.BackgroundColor = UIColor.Clear;
    line.Frame = new CGRect(0, 0, View.Frame.Width, 2);
    var maskLayer = new CAShapeLayer();
    UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(line.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(18.0, 18.0));
    maskLayer.Path = bezierPath.CGPath;
    maskLayer.Frame = line.Bounds;
    maskLayer.StrokeColor = UIColor.Black.CGColor; //set the borderColor
    maskLayer.FillColor = UIColor.Black.CGColor;   //set the background color
    maskLayer.LineWidth = 1;  //set the border width
    line.Layer.AddSublayer(maskLayer);
    View.BackgroundColor = UIKit.UIColor.FromRGB(255, 215, 0);
    UIScrollView scrollView = new UIScrollView();
    scrollView = new UIScrollView
    {
        Frame = new CGRect(0, 0, View.Frame.Width, h + 2 * padding),
        ContentSize = new SizeF((w + padding) * 7, (h + padding) * n),
        BackgroundColor = UIColor.White,
        AutoresizingMask = UIViewAutoresizing.FlexibleWidth
    };
    banner.Image = UIImage.FromResource(null, "OML_iOS.Resources.drawable.Banner.jpg");
    banner.Frame = new RectangleF(0, 0, (float)width, 73);
    banner.ContentMode = UIViewContentMode.ScaleAspectFit;

    dsAdditionalData = myOMLService.GetAdditionalDataFields(Utils.MyUser.Username, Utils.MyUser.Password, Utils.MyCompanyInfo.Company);

    if (dsAdditionalData.Tables[0].Rows.Count > 0)
    {
        {
            foreach (DataRow datarow in dsAdditionalData.Tables[0].Rows)
            {
                UILabel lbl = new UILabel();
                lbl.AccessibilityLabel = datarow["ID"].ToString(); // to retreive any data
                lbl.Text = datarow["Title"].ToString();
                lbl.TextColor = UIColor.Blue;
                labellist.Add(lbl);

                UITextField txt = new UITextField();
                txt.AccessibilityLabel = datarow["ID"].ToString();
                if (action.ToUpper() == "EDITREG" || action.ToUpper() == "EDIT")
                {
                    txt.Text = myOMLService.GetAdditionalDataFieldDataByID(Utils.MyUser.Username, Utils.MyUser.Password, emplyoyeeid, datarow["ID"].ToString());
                }
                fieldlist.Add(txt);
            }
        }
    }

    scrollView.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
    int x = 0;
    UITextField MyTextField = new UITextField();
    foreach (UILabel Mylabel in labellist) {
        scrollView .Add(Mylabel);
        MyTextField = fieldlist[x];
        scrollView.Add(MyTextField);
        if (x == 0)
        {
            Mylabel.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor, 5f).Active = true;
            Mylabel.LeadingAnchor.ConstraintEqualTo(scrollView.LeadingAnchor).Active = true;
            MyTextField.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor, 5f).Active = true;
            MyTextField.LeadingAnchor.ConstraintEqualTo(scrollView.TrailingAnchor).Active = true;
        } else
        {
            Mylabel.TopAnchor.ConstraintEqualTo(labellist[x].BottomAnchor, 5f).Active = true;
            Mylabel.LeadingAnchor.ConstraintEqualTo(scrollView.LeadingAnchor).Active = true;
            MyTextField.TopAnchor.ConstraintEqualTo(labellist[x].TopAnchor, 5f).Active = true;
           MyTextField.LeadingAnchor.ConstraintEqualTo(labellist[x].TrailingAnchor).Active = true;
        }
        x += 1;
    }
    var margins = View.LayoutMarginsGuide;
    View.Add(banner);
    View.Add(employeeimage);
    View.Add(btnSave);
    View.Add(lblAgeAsOf);
    View.Add(line);
    View.Add(scrollView);
    View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();

    banner.LeadingAnchor.ConstraintEqualTo(margins.LeadingAnchor).Active = true;
    banner.TrailingAnchor.ConstraintEqualTo(margins.TrailingAnchor).Active = true;
    banner.TopAnchor.ConstraintEqualTo(TopLayoutGuide.GetBottomAnchor()).Active = true;
    employeeimage.LeadingAnchor .ConstraintEqualTo(margins.LeadingAnchor).Active = true;
    employeeimage.TopAnchor.ConstraintEqualTo(banner.BottomAnchor).Active = true;
    btnSave.LeadingAnchor.ConstraintEqualTo(employeeimage.TrailingAnchor, 10f).Active = true;
    btnSave.TopAnchor.ConstraintEqualTo(employeeimage.TopAnchor).Active = true;
    lblAgeAsOf.LeadingAnchor.ConstraintEqualTo(margins.LeadingAnchor).Active = true;
    lblAgeAsOf.TopAnchor.ConstraintEqualTo(employeeimage.BottomAnchor).Active = true;
    line.LeadingAnchor.ConstraintEqualTo(margins.LeadingAnchor).Active = true;
    line.TopAnchor.ConstraintEqualTo(lblAgeAsOf.BottomAnchor,5f).Active = true;
    scrollView.LeadingAnchor.ConstraintEqualTo(margins.LeadingAnchor).Active = true;
    scrollView.TopAnchor.ConstraintEqualTo(line.BottomAnchor).Active = true;
    scrollView.BottomAnchor.ConstraintEqualTo(margins.BottomAnchor).Active = true;
}

As I had said, the app compiles and runs with no errors. The issue is that the scrollView doesn't appear. The data elements (UILabel and UITextField) are created and added to the scrollView, but nothing appears. I usually use the Cirrious FluentLayouts NUGet plugin to create the constraints, but I wanted to expand my knowledge of constraints and I'm trying anchors. It apparently isn't going well. Can anyone tell me what I'm doing wrong?


Solution

  • Well, I was unable to figure out why the scrollview wasn't appearing and no one was able to assist (apparently). So I went back to the Cirrious FluentLayouts NuGet package I was using on my other views. This (apparenlty) solved the problem of the scrollview displaying. I was also able to find a solution to my display of the user defined fields at this link Adding nested stackviews programmatically using xamarin.ios c#. My Code:

    public override void ViewDidLoad()
    {
           var NavBarHeight = UIApplication.SharedApplication.StatusBarFrame.Size.Height +
                              (NavigationController?.NavigationBar.Frame.Height ?? 0.0);
           nfloat height = View.Bounds.Height;
           nfloat width = View.Bounds.Width;
           float padding = 10.0f;
           int n = 20;
           float h = 50.0f;
           float w = 50.0f;
           UIStackView verticalStack = new UIStackView();
           verticalStack.Axis = UILayoutConstraintAxis.Vertical;
           verticalStack.TranslatesAutoresizingMaskIntoConstraints = false;
           UIImageView banner = new UIImageView();
           UIImageView employeeimage = new UIImageView();
           employeeimage.Frame = new RectangleF(0f, 0f, (float)imageWidth, (float)imageHeight);
           UIImage Mybitmap = Utils.GetImagefromByteArray(imageBytes);
           employeeimage.Image = Mybitmap;
           UIButton btnSave = new UIButton();
           btnSave.SetTitle("Save", UIControlState.Normal);
           btnSave.SetTitleColor(UIColor.Black, UIControlState.Normal);
           btnSave.BackgroundColor = UIKit.UIColor.FromRGB(255, 215, 0);
           btnSave.HorizontalAlignment = UIControlContentHorizontalAlignment.Left;
           btnSave.Layer.BorderWidth = 1;
           btnSave.Frame = new CGRect(0, 0f, 75f, 26);
           UILabel lblAgeAsOf = new UILabel();
           lblAgeAsOf.Text = "Age as of: ";
           List<UILabel> labellist = new List<UILabel>();
           List<UITextField> fieldlist = new List<UITextField>();
           UIView line = new UIView();
           line.BackgroundColor = UIColor.Clear;
           line.Frame = new CGRect(0, 0, View.Frame.Width, 2);
           var maskLayer = new CAShapeLayer();
           UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(line.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(18.0, 18.0));
           maskLayer.Path = bezierPath.CGPath;
           maskLayer.Frame = line.Bounds;
           maskLayer.StrokeColor = UIColor.Black.CGColor; //set the borderColor
           maskLayer.FillColor = UIColor.Black.CGColor;   //set the background color
           maskLayer.LineWidth = 1;  //set the border width
           line.Layer.AddSublayer(maskLayer);
           UILabel lblName = new UILabel();
           lblName.Text = name;
    
           View.BackgroundColor = UIKit.UIColor.FromRGB(255, 215, 0);
           UIScrollView scrollView = new UIScrollView();
           scrollView = new UIScrollView
           {
               Frame = new CGRect(0, 0, View.Frame.Width, h + 2 * padding),
               ContentSize = new SizeF((w + padding) * 7, (h + padding) * n),
               BackgroundColor = UIColor.White,
               AutoresizingMask = UIViewAutoresizing.FlexibleWidth
           };
    
           banner.Image = UIImage.FromResource(null, "iOS.Resources.drawable.Banner.jpg");
           banner.Frame = new RectangleF(0, 0, (float)width, 73);
           banner.ContentMode = UIViewContentMode.ScaleAspectFit;
           dsAdditionalData = myService.GetAdditionalDataFields(Utils.MyUser.Username, Utils.MyUser.Password, Utils.MyCompanyInfo.Company);
    
           if (dsAdditionalData.Tables[0].Rows.Count > 0)
           {
               {
                   foreach (DataRow datarow in dsAdditionalData.Tables[0].Rows)
                   {
                       UIStackView horizontalStack = new UIStackView();
                       horizontalStack.Distribution = UIStackViewDistribution.EqualSpacing;
                       horizontalStack.Axis = UILayoutConstraintAxis.Horizontal;
                       // UIStackView should use AddArrangedSubview() to add subviews.
    
                       UILabel lbl = new UILabel();
                       lbl.AccessibilityLabel = datarow["ID"].ToString();
                       lbl.Text = datarow["Title"].ToString();
                       lbl.TextColor = UIColor.Blue;
                       //labellist.Add(lbl);
    
                       UITextField txt = new UITextField();
                       txt.Placeholder = "Enter " + datarow["Title"].ToString();
                       txt.AccessibilityLabel = datarow["ID"].ToString(); // to link the data input to the field
                       if (action.ToUpper() == "EDITREG" || action.ToUpper() == "EDIT")
                       {
                           txt.Text = myService.GetAdditionalDataFieldDataByID(Utils.MyUser.Username, Utils.MyUser.Password, employeeid, datarow["ID"].ToString());
                       }
                       horizontalStack.AddArrangedSubview(lbl);
                       horizontalStack.AddArrangedSubview(txt);
                       //fieldlist.Add(txt);
                       verticalStack.AddArrangedSubview(horizontalStack);
                   }
               }
           }
           scrollView.Add(verticalStack);
           scrollView.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
    
           View.Add(banner);
           View.Add(employeeimage);
           View.Add(btnSave);
           View.Add(lblName);
           View.Add(lblAgeAsOf);
           View.Add(line);
           View.Add(scrollView);
           View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
    
           View.AddConstraints
           (
               banner.AtTopOf(View, (float)NavBarHeight),
               banner.AtRightOf(View, 0),
               banner.AtLeftOf(View, 0),
    
               playerimage.Below(banner, 2),
               playerimage.Height().EqualTo(180),
               playerimage.Width().EqualTo(180),
    
               btnSave.AtTopOf(employeeimage),
               btnSave.ToRightOf(employeeimage, 5),
    
               lblName.Below(employeeimage, 2),
               lblName.WithSameWidth(banner),
    
               lblAgeAsOf.Below(lblName, 0),
               lblAgeAsOf.WithSameWidth(banner),
    
               line.Below(lblAgeAsOf, 0),
               line.WithSameWidth(banner),
               line.Height().EqualTo(2),
    
               scrollView.Below(line, 0),
               scrollView.AtBottomOf(View, 10),
               scrollView.AtLeftOf(View, 10),
               scrollView.AtRightOf(View, 10)
           );
       }