【问题标题】:Get data from selected cell in collection vew cell从collectionview单元格中的选定单元格获取数据
【发布时间】:2021-01-19 02:54:18
【问题描述】:

我有一个存储员工 ID 的功能集合视图,当单元格被选中时,我需要从单元格中获取该数据。我创建了一个UICollectionViewDelegate,在其中获取视图集合中所选视图的索引,但返回的cell 没有我存储员工ID 的属性。我已经到处寻找解决方案,但没有解决我的具体问题,而且我尝试过的任何工作都没有。我的代码:

集合视图:

public partial class Participants : UIViewController
{
    public User MyUser;
    public string company = "";
    public string department = "";
    public string section = "";
    public Participants(IntPtr handle) : base(handle)
    {
    }
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        DataInterfaceWeb.DataInterface myService = new DataInterfaceWeb.DataInterface();
        DataSet dbParticipants = myService.GetParticipantsWithPhoto(MyUser.Username, MyUser.Password, company, department, section, "CURRENT");

        View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
        var height = this.NavigationController.NavigationBar.Bounds.Height;
        var width = this.NavigationController.NavigationBar.Bounds.Width;

        viewParticipants.AddConstraints(

            banner.AtTopOf(View, height),
            banner.AtRightOf(View, 0),
            banner.AtLeftOf(View, 0),

            lblTitle.Below(banner, 0),
            lblTitle.WithSameWidth(banner)
            , cvParticipants.Below(lblTitle, 0),
            cvParticipants.WithSameWidth(lblTitle),
            cvParticipants.AtLeftOf(View, 10),
            cvParticipants.AtRightOf(View, 10),
            cvParticipants.AtBottomOf(View,10)
        );

        cvParticipants.CollectionViewLayout = new UICollectionViewFlowLayout()
        {
            ItemSize = new CGSize((float)UIScreen.MainScreen.Bounds.Size.Width / 2.15f, (float)UIScreen.MainScreen.Bounds.Size.Width / 2.15f),
            HeaderReferenceSize = new CGSize(25, 25),
            SectionInset = new UIEdgeInsets(0, 0, 0, 0),
            ScrollDirection = UICollectionViewScrollDirection.Vertical,
            MinimumInteritemSpacing = 0, // minimum spacing between cells
            MinimumLineSpacing = 0,
            // minimum spacing between rows if ScrollDirection is Vertical or between columns if Horizontal
            
        };

        cvParticipants.RegisterClassForCell(typeof(ParticipantCell), ParticipantCell.participantCellId);

        cvParticipants.Source = new CVSource(dbParticipants);

        cvParticipants.Delegate = new ParticipantDelegate();

        cvParticipants.BackgroundColor = UIKit.UIColor.FromRGB(255, 215, 0);

        cvParticipants.ReloadData();

        lblTitle.Text = team + " Participants";

    }

}

细胞类:

class ParticipantCell : UICollectionViewCell
{
    UIImageView imageView { get; set; }
    UILabel lblName { get; set; }

    string EmployeeID { get; set; }        

    public static NSString participantCellId = new NSString("ParticipantCell");
    [Export("initWithFrame:")]
    public ParticipantCell(CGRect frame) : base(frame)
    {

        ContentView.Layer.BorderColor = UIColor.LightGray.CGColor;
        ContentView.Layer.BorderWidth = 2.0f;
        ContentView.BackgroundColor = UIColor.White;
        ContentView.Transform = CGAffineTransform.MakeScale(0.8f, 0.8f);



        imageView = new UIImageView(UIImage.FromBundle("placeholder.png"));
        imageView.Center = ContentView.Center;
        imageView.ContentMode = UIViewContentMode.ScaleAspectFit;
        lblName = new UILabel();

        ContentView.AddSubview(new UIView() { imageView, lblName });
    }
    public void SetImage (UIImage image, string name, string playerID)
    {
        EmployeeID = employeeID;
        imageView.Image = image;
        imageView.Frame = new CGRect(0, 0, ContentView.Bounds.Width, ContentView.Bounds.Height);
        lblName.Text = name;
        lblName.Frame = new CGRect(0, ContentView.Bounds.Height, ContentView.Bounds.Width, 26);
    }

}

视图控制器和源类:

class ParticipantViewController : UIViewController
{
    static NSString participantCellId = new NSString("ParticipantCell");
    public DataSet Participants;
    UICollectionView collectionView;
    CVSource source;
    public ParticipantViewController(UICollectionViewLayout layout, DataSet pParticipants) //: base(layout)
    {

        Participants = pParticipants;
        collectionView = new UICollectionView(UIScreen.MainScreen.Bounds, layout);
        collectionView.ContentSize = View.Frame.Size;

        source = new CVSource(pParticipants);

        collectionView.RegisterClassForCell(typeof(ParticipantCell), participantCellId);
        collectionView.Source = source;
    }

    public override void ViewDidLoad()
    {

        View = collectionView;

    }

}
class CVSource : UICollectionViewSource
{
    DataSet Participants = new DataSet();

    public override nint NumberOfSections(UICollectionView collectionView)
    {
        return 1;
    }
    public override nint GetItemsCount(UICollectionView collectionView, nint section)
    {
        return Participants.Tables[0].Rows.Count;
    }

    public CVSource(DataSet pParticipants)
    {
        Participants = pParticipants;
    }

    public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var participantCell = (ParticipantCell)collectionView.DequeueReusableCell(ParticipantCell.participantCellId, indexPath);
        string name = Participants.Tables[0].Rows[indexPath.Row]["Name"].ToString();
        byte[] imageBytes = (byte[])Participants.Tables[0].Rows[indexPath.Row]["Photo"];
        string employeeid= Participants.Tables[0].Rows[indexPath.Row]["employeeid"].ToString();
        UIImage Mybitmap = GetImagefromByteArray(imageBytes);
        participantCell.SetImage(Mybitmap, name, playerid); // MaxResizeImage(Mybitmap, 200f, 200f);
        return participantCell;
    }

    public static UIImage GetImagefromByteArray(byte[] imageBuffer)
    {
        NSData imageData = NSData.FromArray(imageBuffer);
        return UIImage.LoadFromData(imageData);
    }
}

最后是我捕获所选单元格的代表:

class ParticipantDelegate : UICollectionViewDelegate
{
    public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var cell = collectionView.CellForItem(indexPath);
    }
} 

cell 不包含在participantCell 中定义的任何属性,我需要这些信息。其他一切都按预期工作。

【问题讨论】:

  • 您需要将从CellForItem 检索到的单元格从UICollectionViewCell 向下转换为ParticipantCell,但实际上您应该从数据源而不是单元格中检索数据。单元格只是数据的“视图”。
  • 好的,如何访问collectionView的源?我试过var source = collectionView.Source,把Participants Dataset设为类的属性,但是Participants属性不可访问,
  • 好吧,看来ParticipantCell cell = (ParticipantCell)collectionView.CellForItem(indexPath) 成功了。如果您想将其作为答案,我将其标记为这样。感谢您的帮助!
  • 您的集合视图的委托通常是您的视图控制器,因此可以访问Participants 属性。如果你想将你的委托作为一个单独的对象,你可以在构造它时将Participants 传递给它。
  • @Paulw11,请参阅我上面的评论。你之前的评论解决了。

标签: c# ios xamarin xamarin.ios


【解决方案1】:

正确的方法应该是将Participants 传递给您的delegate 类,就像您在CVSource 中所做的那样:

class ParticipantDelegate : UICollectionViewDelegate
{
    DataSet Participants = new DataSet();

    public ParticipantDelegate(DataSet pParticipants)
    {

        Participants = pParticipants;

    }

    public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var cell = collectionView.CellForItem(indexPath);
        
        //get the data
        var cellData = Participants.Tables[0].Rows[indexPath.Row];

        //For example
        string name = Participants.Tables[0].Rows[indexPath.Row]["Name"].ToString();
    }
}

并设置委托:

cvParticipants.Delegate = new ParticipantDelegate(dbParticipants);

【讨论】:

  • 好的,这也可以。与@Paulw11 之前建议的方法相比,是什么让这成为“正确的方法”?
  • Paulw11 在评论中说您应该从数据源而不是单元格中检索数据。嗯,用他的方法就好了。
  • @PrescottChartier 如果我的回答对您有帮助,请您接受(点击此回答左上角的☑️),以便我们可以帮助更多有同样问题的人:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
相关资源
最近更新 更多