the programming language descargar apple ios swift swift3 tvos

ios - descargar - the swift programming language pdf



¿Cómo centrar las celdas de un UICollectionView en Swift3.0? (7)

Descripción:

Respuesta para Objective-C y Swift2.0 : ¿Cómo centrar las celdas de un UICollectionView?

Por lo general, intentaría convertir la respuesta Swift2.0 a la solución Swift3.0 , sin embargo, el método:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2 return UIEdgeInsetsMake(0, edgeInsets, 0, 0); }

no parece existir en Swift3.0 , y el único otro método que encontré que parece útil es:

func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout { <#code#> }

pero no estoy seguro de cómo implementarlo correctamente.

Pregunta:

¿Cómo centrar las celdas de un UICollectionView en Swift3.0 ?

(Una solución simple y general para iOS y tvOS sería perfecta)


El método que está buscando está presente con una firma diferente en Swift 3 . La nueva firma es esta:

optional public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets

PD: este método está presente en el protocolo UICollectionViewDelegateFlowLayout .
Espero que esto ayude.


Suponiendo que se está conformando con UICollectionViewDelegateFlowLayout , debería ser:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2 return UIEdgeInsets(top: 0, left: edgeInsets, bottom: 0, right: 0) }


func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let allCellWidth = KcellWidth * numberOfCell let cellSpacingWidth = CellSpacing * (numberOfCell - 1) let leftInset = (collectionViewWidth - CGFloat(allCellWidth + cellSpacingWidth)) / 2 let rightInset = leftInset return UIEdgeInsetsMake(0, leftInset, 0, rightInset) }


Si bien la respuesta de rottenoats es excelente, tiene un error de espaciado adicional y no utiliza gran parte de la sintaxis de swift 3 disponible. Lo solucioné y reduje la cantidad de dependencias a las variables locales.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { // Make sure that the number of items is worth the computing effort. guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout, let dataSourceCount = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: section), dataSourceCount > 0 else { return .zero } let cellCount = CGFloat(dataSourceCount) let itemSpacing = flowLayout.minimumInteritemSpacing let cellWidth = flowLayout.itemSize.width + itemSpacing var insets = flowLayout.sectionInset // Make sure to remove the last item spacing or it will // miscalculate the actual total width. let totalCellWidth = (cellWidth * cellCount) - itemSpacing let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right // If the number of cells that exist take up less room than the // collection view width, then center the content with the appropriate insets. // Otherwise return the default layout inset. guard totalCellWidth < contentWidth else { return insets } // Calculate the right amount of padding to center the cells. let padding = (contentWidth - totalCellWidth) / 2.0 insets.left = padding insets.right = padding return insets }

NB: Este fragmento solo funciona para un desplazamiento horizontal, pero se puede ajustar fácilmente.


En lugar de agregar este código cada vez en su método de delegado, puede agregar la clase de diseño de flujo personalizado a su collectionView. linkToSuchLayout


Esta terminó siendo la solución que utilicé. Lea los comentarios del código para una mejor comprensión. Swift 3.0

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { //Where elements_count is the count of all your items in that //Collection view... let cellCount = CGFloat(elements_count) //If the cell count is zero, there is no point in calculating anything. if cellCount > 0 { let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing //20.00 was just extra spacing I wanted to add to my cell. let totalCellWidth = cellWidth*cellCount + 20.00 * (cellCount-1) let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right if (totalCellWidth < contentWidth) { //If the number of cells that exists take up less room than the //collection view width... then there is an actual point to centering them. //Calculate the right amount of padding to center the cells. let padding = (contentWidth - totalCellWidth) / 2.0 return UIEdgeInsetsMake(0, padding, 0, padding) } else { //Pretty much if the number of cells that exist take up //more room than the actual collectionView width, there is no // point in trying to center them. So we leave the default behavior. return UIEdgeInsetsMake(0, 40, 0, 40) } } return UIEdgeInsets.zero }


Ligera adaptación de @rottenoats respuesta. Esto es más genérico

Lo más importante, recuerde hacer que su controlador de vista se ajuste al protocolo UICollectionViewDelegateFlowLayout.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return .zero } let cellCount = CGFloat(collectionView.numberOfItems(inSection: section)) if cellCount > 0 { let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing let totalCellWidth = cellWidth * cellCount let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right - flowLayout.headerReferenceSize.width - flowLayout.footerReferenceSize.width if (totalCellWidth < contentWidth) { let padding = (contentWidth - totalCellWidth + flowLayout.minimumInteritemSpacing) / 2.0 return UIEdgeInsetsMake(0, padding, 0, 0) } } return .zero }