By Khaksar


2018-09-14 15:57:20 8 Comments

I have UITableViewController, inside that, I added a button in the Cell. Upon clicking the button, it shows a UIAlertController with "Ok" & "Cancel" Actions.

In my UIAlertController, I added a UIPickerView with some options.

When user clicks on the button in the cell, UIAlertController Popsup and shows the UIPickerView inside AlertBox with "OK" & "Cancel" actions.

Can you please help me in finding the value Selected by UIPickerView upon clicking the "Ok" button of UIAlertController.

namespace Navigation
{
public partial class ReviewInspectionViewController : UIViewController
{

    private string filePath;
    private InspectionData inspData = null;

    List<ReportObservation> lstCriticalObs = new List<ReportObservation>();
    List<ReportObservation> lstNonCriticalObs = new List<ReportObservation>();

    public Audits Audit
    {
        get
        {
            return this._audit;
        }
        set
        {
            this._audit = value;
        }
    }

    public ReviewInspectionViewController(IntPtr handle) : base(handle)
    {
    }

    public override void ViewWillAppear(bool animated)
    {
        base.ViewWillAppear(animated);
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        filePath = InProgressPath + Audit.AssessmentId.ToString() + ".xml";
        inspData = ReadInspectionData(filePath);

        if (inspData != null)
        {
            for (int i = 0; i < inspData.ReportSections.Count; i++)
            {
                lstCriticalObs.AddRange(inspData.ReportSections[i].ReportObservations.FindAll(x => x.Critical == true));
            }
            for (int i = 0; i < inspData.ReportSections.Count; i++)
            {
                lstNonCriticalObs.AddRange(inspData.ReportSections[i].ReportObservations.FindAll(x => x.Critical == false));
            }

            tblReviewInspection.Source = new ReviewInspectionSource(this, inspData, lstCriticalObs, lstNonCriticalObs);
            tblReviewInspection.RowHeight = 160.0f;
        }
    }
}

class ReviewInspectionSource : UITableViewSource
{
    NSString _cellID = new NSString("TableCell");
    ReviewInspectionViewController _parent;
    private InspectionData _inspectionData;
    private List<ReportObservation> _lstCriticalObs;
    private List<ReportObservation> _lstNonCriticalObs;
    UITableView tvStatus;

    public ReviewInspectionSource(ReviewInspectionViewController parent,
                                  InspectionData inspectionData,
                                  List<ReportObservation> lstCriticalObs,
                                  List<ReportObservation> lstNonCriticalObs)
    {
        _inspectionData = inspectionData;
        _lstCriticalObs = lstCriticalObs;
        _lstNonCriticalObs = lstNonCriticalObs;
        _parent = parent;
    }

    public override nint NumberOfSections(UITableView tableView)
    {
        return _lstCriticalObs.Count;
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        int cnt = _lstCriticalObs[Convert.ToInt32(section)].ReportFindings.Count;
        return cnt;
    }

    public override UIView GetViewForHeader(UITableView tableView, nint section)
    {
        UIView ctrls = new UIView();
        tvStatus = new UITableView();
        UILabel headerLabel = new UILabel(new CGRect(55, 4, 350, 33)); // Set the frame size you need
        headerLabel.TextColor = UIColor.Red; // Set your color
        headerLabel.Text = _lstCriticalObs[Convert.ToInt32(section)].ObsTitle;

        UIButton btnEdit = new UIButton(new CGRect(5, 4, 50, 33));
        var newFont = UIFont.SystemFontOfSize(17);
        btnEdit.SetTitle("Edit", UIControlState.Normal);
        btnEdit.Font = newFont;
        btnEdit.BackgroundColor = UIColor.Yellow;
        btnEdit.SetTitleColor(UIColor.Black, UIControlState.Normal);
        btnEdit.SetTitleColor(UIColor.Black, UIControlState.Selected);

        btnEdit.TouchUpInside += (object sender, EventArgs e) =>
         {
             tvStatus.Frame = new CGRect(((UIButton)sender).Frame.X, ((UIButton)sender).Frame.Y, 50, 230);
             tvStatus.Hidden = false;
             btnEdit.Hidden = true;
             //string msg = "SectionIndex: " + section;
             var Alert = UIAlertController.Create("Inspection", "\n\n\n\n\n\n", UIAlertControllerStyle.Alert);
             Alert.ModalInPopover = true;
            var picker = new UIPickerView(new CGRect(5, 20, 250, 140)) ;

             picker.Model = new ObsStatusModel();

             Alert.View.AddSubview(picker);

             Alert.AddTextField((field) => {
                 field.Placeholder = "email address";
             });

             Alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (action) => {

            }));
             Alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null ));
             UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(Alert, true, null);
             /*

            @IBAction func showChoices(_ sender: Any) {
              let alert = UIAlertController(title: "Car Choices", message: "\n\n\n\n\n\n", preferredStyle: .alert)
              alert.isModalInPopover = true

              let pickerFrame = UIPickerView(frame: CGRect(x: 5, y: 20, width: 250, height: 140))

              alert.view.addSubview(pickerFrame)
              pickerFrame.dataSource = self
              pickerFrame.delegate = self

              alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
              alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (UIAlertAction) in

                  print("You selected " + self.typeValue )

              }))
              self.present(alert,animated: true, completion: nil )
            }
          */
         };


        List<string> lstStatus = new List<string>();
        lstStatus.Add(" "); lstStatus.Add("IN"); lstStatus.Add("OUT"); lstStatus.Add("N/A"); lstStatus.Add("N/O");

        tvStatus.Source = new StatusSource(lstStatus);

        tvStatus.Layer.BorderColor = new CGColor(0, 0, 0);
        tvStatus.Layer.BorderWidth = 2;
        tvStatus.BackgroundColor = UIColor.White;
        tvStatus.Hidden = true;
        // tvStatus.Layer.ZPosition = 1;
        tvStatus.ResignFirstResponder();

        // btnEdit.BringSubviewToFront(tvStatus);
        // btnEdit.Layer.ZPosition = 0;

        //UILabel editLabel = new UILabel(new CGRect(360, 4, 100, 33)); // Set the frame size you need
        //editLabel.TextColor = UIColor.Green; // Set your color
        //editLabel.Text = "Edit Label";

        ctrls.AddSubviews(headerLabel, btnEdit, tvStatus);

        return ctrls;
    }

    public override nfloat GetHeightForHeader(UITableView tableView, nint section)
    {
        nfloat height = 50.0f;
        return height;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        string msg = "Selected Row, ReviewInspection -- SectionIndex: " + indexPath.Section.ToString() + " RowIndex: " + indexPath.Row;
        tvStatus.Hidden = true;
        tvStatus.ResignFirstResponder();
        //var Alert = UIAlertController.Create("Inspection", msg, UIAlertControllerStyle.Alert);

        //Alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
        //UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(Alert, true, null);
    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        ReportFinding currentRequirementItem = _lstCriticalObs[indexPath.Section].ReportFindings[indexPath.Row]; // _inspectionData.ReportSections[indexPath.Row];

        var cell = tableView.DequeueReusableCell(_cellID) as ReviewInspectionTableCell;

        if (cell == null) { cell = new ReviewInspectionTableCell(_cellID); }

        UIView customColorView = new UIView();
        customColorView.BackgroundColor = UIColor.FromRGB(39, 159, 218);

        UIView SelectedRowcustomColorView = new UIView();
        SelectedRowcustomColorView.BackgroundColor = UIColor.FromRGB(255, 255, 255);

        UIColor clrChecklistButton = UIColor.White;
        UIColor clrFont = UIColor.White;

        cell.TextLabel.LineBreakMode = UILineBreakMode.WordWrap;
        cell.PreservesSuperviewLayoutMargins = false;
        cell.LayoutMargins = UIEdgeInsets.Zero;
        cell.BackgroundView = customColorView;
        cell.SelectedBackgroundView = SelectedRowcustomColorView;

        cell.Edit.TouchUpInside += (object sender, EventArgs e) =>
        {
            string msg = "SectionIndex: " + indexPath.Section.ToString() + " RowIndex: " + indexPath.Row;
            var Alert = UIAlertController.Create("Inspection", msg, UIAlertControllerStyle.Alert);

            Alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(Alert, true, null);

        };

        cell.Delete.TouchUpInside += (object sender, EventArgs e) =>
        {
            string msg = "SectionIndex: " + indexPath.Section.ToString() + " RowIndex: " + indexPath.Row;
            var Alert = UIAlertController.Create("Inspection", msg, UIAlertControllerStyle.Alert);

            Alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(Alert, true, null);

        };

        cell.UpdateCellControlsWithAuditData(currentRequirementItem.ViolationText,
                                             currentRequirementItem.FindingAnswer,
                                             currentRequirementItem.RepeatViolation,
                                             clrChecklistButton,
                                             clrFont);
        return cell;
    }
}

public class ReviewInspectionTableCell : UITableViewCell
{
    UILabel violationText, findingAnswer, repeatViolation;
    UIButton btnEdit, btnDelete;
    public ReviewInspectionTableCell(NSString cellId) : base(UITableViewCellStyle.Default, cellId)
    {
        SelectionStyle = UITableViewCellSelectionStyle.Gray;
        ContentView.BackgroundColor = UIColor.FromRGB(110, 214, 254);
        ContentView.Layer.CornerRadius = 8;

        var newFont = UIFont.SystemFontOfSize(17);
        violationText = new UILabel();
        violationText.Font = newFont;
        violationText.LineBreakMode = UILineBreakMode.WordWrap;
        violationText.TextAlignment = UITextAlignment.Left;
        violationText.Lines = 0;
        violationText.TextColor = UIColor.White;
        violationText.HighlightedTextColor = UIColor.Green;
        violationText.BackgroundColor = UIColor.Gray;

        findingAnswer = new UILabel();
        findingAnswer.Font = newFont;
        findingAnswer.BackgroundColor = UIColor.Orange;
        findingAnswer.LineBreakMode = UILineBreakMode.WordWrap;
        findingAnswer.TextAlignment = UITextAlignment.Left;
        findingAnswer.Lines = 0;
        findingAnswer.TextColor = UIColor.White;

        repeatViolation = new UILabel();
        repeatViolation.Font = newFont;
        repeatViolation.BackgroundColor = UIColor.Purple;

        btnEdit = new UIButton();
        btnEdit.Font = newFont;
        btnEdit.SetTitle("Edit", UIControlState.Normal);
        btnEdit.SetTitleColor(UIColor.Black, UIControlState.Selected);

        btnDelete = new UIButton();
        btnDelete.Font = newFont;
        btnDelete.SetTitle("Delete", UIControlState.Normal);
        btnDelete.SetTitleColor(UIColor.Black, UIControlState.Selected);

        ContentView.AddSubviews(new UIView[] { violationText, findingAnswer, repeatViolation, btnEdit, btnDelete });
    }

    public UIButton Delete
    {
        get
        {
            return btnDelete;
        }
    }
    public UIButton Edit
    {
        get
        {
            return btnEdit;
        }
    }

    public void UpdateCellControlsWithAuditData(string _violationText,
                                                string _findingAnswer,
                                                Boolean _repeatVilation,
                                                UIColor btnColor,
                                                UIColor clrFont)
    {
        string repeat = string.Empty;
        if (_repeatVilation)
        {
            repeat = "Repeat Violation.";
        }
        violationText.Text = _violationText;
        findingAnswer.Text = _findingAnswer;
        repeatViolation.Text = repeat;
    }

    public override void LayoutSubviews()
    {
        base.LayoutSubviews();
        //x, y, width, height
        violationText.Frame = new CGRect(50, 0, 700, 80);
        findingAnswer.Frame = new CGRect(50, 81, 700, 33);
        repeatViolation.Frame = new CGRect(50, 110, 350, 33);

        btnEdit.Frame = new CGRect(5, 0, 50, 33);
        btnEdit.Layer.CornerRadius = 8;
        btnEdit.BackgroundColor = UIColor.FromRGB(19, 120, 170);
        btnDelete.Frame = new CGRect(5, 34, 50, 33);
        btnDelete.Layer.CornerRadius = 8;
        btnDelete.BackgroundColor = UIColor.FromRGB(19, 120, 170);
    }
}

public class ObsStatusModel : UIPickerViewModel
{
    static string[] names = new string[] {
        "Monitor",
        "Comprehensive",
        "OutBreak Investigation",
        "Complaint",
        "FollowUp",
        "PlanReview",
        "Other"
        };

    public ObsStatusModel()
    {

    }

    public override nint GetComponentCount(UIPickerView v)
    {
        return 1;
    }

    public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
    {
        return names.Length;
    }

    public override string GetTitle(UIPickerView picker, nint row, nint component)
    {

        return names[row];

    }

}

class StatusSource : UITableViewSource
{
    NSString _cellID = new NSString("TableCell");

    private List<string> _lstStatus;

    public StatusSource(List<string> lstStatus)
    {
        _lstStatus = lstStatus;

    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return _lstStatus.Count;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {

        var Alert = UIAlertController.Create("Inspection", string.Empty, UIAlertControllerStyle.Alert);

        Alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(Alert, true, null);

    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        string currentStatusItem = _lstStatus[indexPath.Row];

        var cell = tableView.DequeueReusableCell(_cellID) as StatusTableCell;

        if (cell == null) { cell = new StatusTableCell(_cellID); }



        cell.TextLabel.LineBreakMode = UILineBreakMode.WordWrap;
        cell.PreservesSuperviewLayoutMargins = false;
        cell.LayoutMargins = UIEdgeInsets.Zero;

        cell.UpdateCellControlsWithAuditData(currentStatusItem);
        return cell;
    }
}

public class StatusTableCell : UITableViewCell
{
    UILabel statusText;
    public StatusTableCell(NSString cellId) : base(UITableViewCellStyle.Default, cellId)
    {
        SelectionStyle = UITableViewCellSelectionStyle.Gray;
        //ContentView.BackgroundColor = UIColor.FromRGB(110, 214, 254);
        //ContentView.Layer.CornerRadius = 8;

        var newFont = UIFont.SystemFontOfSize(17);
        statusText = new UILabel();
        statusText.Font = newFont;
        statusText.LineBreakMode = UILineBreakMode.WordWrap;
        statusText.TextAlignment = UITextAlignment.Center;
        statusText.Lines = 0;
        statusText.TextColor = UIColor.Black;
        statusText.HighlightedTextColor = UIColor.Green;
        statusText.BackgroundColor = UIColor.White;

        ContentView.AddSubviews(new UIView[] { statusText });
    }

    public void UpdateCellControlsWithAuditData(string status)
    {
        statusText.Text = status;

    }

    public override void LayoutSubviews()
    {
        base.LayoutSubviews();
        //x, y, width, height
        statusText.Frame = new CGRect(5, 5, 100, 25);
    }
}

}

See attached image.

enter image description here

1 comments

@LucasZ 2018-09-18 05:07:26

You can add a UIPickerView as subview on the view of UIAlertViewController. Refer to the following code:

 public void CreatAlertView()
    {

        UIAlertController alert = UIAlertController.Create("Inspection\n\n\n\n\n\n\n", "", UIAlertControllerStyle.Alert);

        alert.AddTextField((UITextField obj) => 
        {
           obj.Placeholder = "email address";


        });

        UIAlertAction OKAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default, (obj) =>
           {
              if(alert.TextFields[0].Text.Length!=0)
              {
                //do some thing
              }
           });

        UIAlertAction CancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null);

        alert.AddAction(OKAction);
        alert.AddAction(CancelAction);

        var picker = new UIPickerView(new CGRect(0, 0,270,220));
        picker.WeakDelegate = this;
        picker.DataSource = this;

        this.pickerView = picker;

        alert.View.AddSubview(pickerView);

        alertController = alert;

        this.PresentViewController(alertController, false, null);
    }

And don't forget to implement the methods in the delegate:

public nint GetComponentCount(UIPickerView pickerView)
  {
     return 1;
  }

public nint GetRowsInComponent(UIPickerView pickerView, nint component)
  {

     if (component==0)
      {
         return (System.nint)itemsArray.Length;
      }

     else
      {
         return 0;
      }
  }

[Export("pickerView:titleForRow:forComponent:")]
public string GetTitle(UIPickerView pickerView, nint row, nint component)
  {
     string content = itemsArray[(nuint)row].ToString();
     return content;
  }

[Export("pickerView:didSelectRow:inComponent:")]
public void Selected(UIPickerView pickerView, nint row, nint component)
  {
     string content= itemsArray[(nuint)row].ToString();
        //do some thing
  }

Then you can call the method

this.itemsArray= new string[] {"apple","google","apple","google","apple","google"} ;//init the source array 

CreatAlertView();

I have upload the demo to my git. you can download it for more details.demo

Related Questions

Sponsored Content

11 Answered Questions

3 Answered Questions

1 Answered Questions

[SOLVED] TableView not displaying text with JSON data from API call

2 Answered Questions

[SOLVED] What is best text container for multiline text in IOS

2 Answered Questions

Why my UIPickerview is not working in UIAlertcontroller?

2 Answered Questions

[SOLVED] How to add UIPickerView in UIAlertController?

1 Answered Questions

[SOLVED] uialertcontroller with uipickerview in swift iOS?

1 Answered Questions

1 Answered Questions

[SOLVED] UITableView text overtop of my custom section header?

  • 2014-03-28 17:51:18
  • Driss Zouak
  • 570 View
  • 1 Score
  • 1 Answer
  • Tags:   ios xamarin

Sponsored Content