Xamarin UIButton有多个事件处理程序

时间:2017-10-25 19:00:40

标签: ios events xamarin uibutton handler

我遇到了在Xamarin内分配了多个事件处理程序的单元格中的UIButtons问题。有没有办法确保只分配一个事件处理程序?我假设在重新加载tableview或collectionview时,这些单元格中的任何内容都将被释放/重置。这是不正确的吗?

这是我在委托中设置单元格的地方:

public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            EventHandler clickTarget = (sender, e) =>
            {
                if (this.parantController.showCategories)
                {
                    this.parantController.apiCallGetBusinessesIndustries(this.parantController.businessesCategoriesResponseModel.business_categories[indexPath.Row].id);
                    this.parantController.showIndustries = true;
                    this.parantController.showCategories = false;
                }
                else  if (this.parantController.showIndustries)
                {
                    this.parantController.apiCallGetBusinessessList("", this.parantController.businessesIndustriesResponseModel.business_industries[indexPath.Row].id);
                    this.parantController.filterView.Hidden = true;
                    this.parantController.showVerticalList = false;
                    this.parantController.showIndustries = false;
                    this.parantController.clearAll = true;
                    this.parantController.filterCollectionView.ReloadData();
                    this.parantController.clearAll = false;
                    //this.parantController.showCategories = true;
                }
            };

            var cell = (FilterCollectionCell)collectionView.DequeueReusableCell("filterCollectionCell", indexPath);
            if (this.parantController.businessesCategoriesResponseModel.business_categories != null && !this.parantController.showIndustries)
            {
                cell.updateCell(false, this.parantController.businessesCategoriesResponseModel.business_categories[indexPath.Row].name, clickTarget);
            }
            if (this.parantController.showIndustries)
            {
                cell.updateCell(false, this.parantController.businessesIndustriesResponseModel.business_industries[indexPath.Row].name, clickTarget);
            }

            return cell;
        }

以下是我将事件处理程序添加到单元格视图控制器中的按钮的代码:

public void updateCell(Boolean selectedFilterType, string title, EventHandler clickHandler) {

        btnFilter.RemoveTarget(this, null, UIControlEvent.AllEvents);

        btnFilter.AddTarget(clickHandler, UIControlEvent.TouchUpInside);// = handlerToUse;

        this.btnFilter.SetTitle(title, UIControlState.Normal);
    }

1 个答案:

答案 0 :(得分:1)

您的GetCell创建应该处理向单元格应用事件,因此当重复使用单元格时,您不会在foreach (var target in button.AllTargets) { button.RemoveTarget(target, null, UIControlEvent.AllTouchEvents); } 方法中每次都附加新事件。

否则你可以检索所有的UButton'每次请求单元格时都会定位并删除它们:

{{1}}