查找UIPickerView选择的值,我在UIAlertController中添加了SubView

问题描述 投票:1回答:1

我有UITableViewController,在里面,我在Cell中添加了一个按钮。单击按钮后,它会显示带有“确定”和“取消”操作的UIAlertController。

在我的UIAlertController中,我添加了一个带有一些选项的UIPickerView。

当用户单击单元格中的按钮时,UIAlertController Popsup并在AlertBox中显示UIPickerView,并显示“确定”和“取消”操作。

你可以帮我找到UIPickerView选择的值,点击UIAlertController的“Ok”按钮。

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

}

见附图。

enter image description here

uitableview xamarin xamarin.ios uipickerview uialertcontroller
1个回答
1
投票

您可以在UIAlertViewController视图中添加UIPickerView作为子视图。请参阅以下代码:

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

并且不要忘记在委托中实现方法:

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
  }

然后你可以调用该方法

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

CreatAlertView();

我已将演示上传到我的git。你可以下载它以获取更多细节.demo

© www.soinside.com 2019 - 2024. All rights reserved.