public void CellsInitialSetup() { if (numberOfCellPrefabs == 0) { return; } rectTransform = GetComponent <RectTransform>(); caroselCells = new CaroselCell[numberOfCellPrefabs]; for (int i = 0; i < numberOfCellPrefabs; i++) { CaroselCell cell = Instantiate(cellPrefab).GetComponent <CaroselCell>(); cell.name = "Cell_" + i; cell.transform.SetParent(rectTransform, false); caroselCells[i] = cell; } width = rectTransform.rect.width; height = rectTransform.rect.height; childWidth = caroselCells[0].GetComponent <RectTransform>().rect.width; childHeight = caroselCells[0].GetComponent <RectTransform>().rect.height; float posOffset = childWidth * 0.5f; for (int i = 0; i < caroselCells.Length; i++) { caroselCells[i].cellIndex = i; Vector2 childPos = caroselCells[i].GetComponent <RectTransform>().localPosition; childPos.x = posOffset + i * (childWidth + itemSpacing); caroselCells[i].GetComponent <RectTransform>().localPosition = childPos; } }
private void HandleHorizontalScroll() { bool swipeRight = dragDirection == DragDirection.Right; // Getting the rightmost or leftmost cell Object depending on swipe direction int currentPrefabIndex = swipeRight ? scrollRect.content.childCount - 1 : 0; var currentItemTransform = scrollRect.content.GetChild(currentPrefabIndex); // Determine whether the cell needs repositioning if (!ReachedThreshold(currentItemTransform)) { return; } // Find the cell object which the current object should be positioned next to int endPrefabIndex = swipeRight ? 0 : scrollRect.content.childCount - 1; Transform endItemTransform = scrollRect.content.GetChild(endPrefabIndex); // Calculate the new position for the cell Vector2 newPos = endItemTransform.position; newPos.x = swipeRight ? endItemTransform.position.x - (scrollContent.ChildWidth + scrollContent.ItemSpacing) : endItemTransform.position.x + (scrollContent.ChildWidth + scrollContent.ItemSpacing); currentItemTransform.position = newPos; // Assign new cell index to the current cell int endItemCellIndex = endItemTransform.GetComponent <CaroselCell>().cellIndex; int currentItemCellIndex = swipeRight ? endItemCellIndex - 1 : endItemCellIndex + 1; CaroselCell currentCell = currentItemTransform.GetComponent <CaroselCell>(); currentCell.cellIndex = currentItemCellIndex; currentItemTransform.SetSiblingIndex(endPrefabIndex); // Update cell content according to the new index // Since it's an endless scroll, the currentItemCellIndex can be very large or very small // Take modular to decide what content to display int totalNumberOfItems = dataSource.GetNumberOfItemsForCaroselView(); int contentIndex = (currentItemCellIndex >= 0) ? currentItemCellIndex % totalNumberOfItems : totalNumberOfItems - Math.Abs(currentItemCellIndex % totalNumberOfItems); dataSource.UpdateCellInCaroselView(currentCell, contentIndex); }
public void UpdateCellInCaroselView(CaroselCell cell, int row) { BookCell bookCell = cell as BookCell; bookCell.bookTitle.text = "Book " + row; }