locked
Click on specific element in UICollectionViewCell not called(instead ItemSelected fired from Source) RRS feed

  • Question

  • User354046 posted

    Hey,

    I have a CollectionView in my Xamarin.iOS projet. I've a button inside my UICollectionViewCell and I'd like to have TouchDown on my button.

    But when I click on this button, ItemSelected fired and not my TouchDown event handler (the global touch on cell called instead of specific touch).

    Could you help me how can I do specify my touch inside any cells pls ? (sorry for my English which is not top)

    here is an ex of my code :

    class MyCollectionViewSource : UICollectionViewSource { List _Datas;

        public MyCollectionViewSource(List<string> datas)
        {
            _Datas = datas;
        }
    
        public override nint GetItemsCount(UICollectionView collectionView, nint section)
        {
            return _Datas.Count;
        }
    
        public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
    
            var view = (MyCollectionViewCell)collectionView.DequeueReusableCell(MyCollectionViewCell.CellId, indexPath);
            return view;
        }
    
        public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
        {
            Console.WriteLine("Row {0} selected", indexPath.Row);
        }
    
        public override bool ShouldSelectItem(UICollectionView collectionView, NSIndexPath indexPath)
        {
            return true;
        }
    }
    
    class MyCollectionViewCell : UICollectionViewCell
    {
        UIView _MyCellView;
    
        public static readonly NSString CellId = new NSString("MyCollectionViewCell");
    
        [Export("initWithFrame:")]
        MyCollectionViewCell(RectangleF frame) : base(frame)
        {
            _MyCellView = new UIView();
            ContentView.AddSubview(_MyCellView);
    
            UIButton btn = new UIButton();
            btn.SetTitle("test", UIControlState.Normal);
            btn.Frame = new CoreGraphics.CGRect(0, 0, 100, 20);
            btn.TouchDown += Btn_TouchDown;
    
            _MyCellView.AddSubview(btn);
    
        // Add some more components to cell 
        }
    
        private void Btn_TouchDown(object sender, EventArgs e)
        {
    
        }
    }
    
    Friday, August 23, 2019 9:39 AM

All replies

  • User369978 posted

    The cell selection was hijacking the touch event , add the following code in MyCollectionViewCell constructor .

    this.ContentView.UserInteractionEnabled = false;
    

    Refer https://stackoverflow.com/a/49686986/8187800.

    Friday, August 23, 2019 12:40 PM