cod*_*tor 22 ios uicollectionview xcode6
我已经实现了一个UICollectionView,单元格大小为w90 h90.当我在iPhone 6上运行时,我在单元格之间获得了适当的间距,但是当我在iPhone 5s上运行时,我在单元格之间获得了更多的间距.我的问题是我如何根据设备屏幕大小更改单元格大小,假设单元格大小为w80 h80,我也可以在iPhone 5s上获得正确的结果.我现在正在做的是
override func viewWillAppear(animated: Bool) {
var scale = UIScreen.mainScreen().scale as CGFloat
println("Scale :\(scale)")
var cellSize = (self.collectionViewLayout as UICollectionViewFlowLayout).itemSize
println("Cell size :\(cellSize)")
imageSize = CGSizeMake(cellSize.width * scale , cellSize.height * scale)
println("Image size : \(imageSize)")
}
Run Code Online (Sandbox Code Playgroud)
// sizeForItemAtIndexPath
func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return imageSize!
}
Run Code Online (Sandbox Code Playgroud)
iPhone 6上的结果:

iPhone 5s的结果

Objective-C/Swift对解决方案都很好.谢谢.
Zai*_*han 35
第1步:实现UICollectionViewDelegateFlowLayout(如果没有完成).
第2步:使用UICollectionViewDelegateFlowLayout的委托方法.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return CGSizeMake((UIScreen.mainScreen().bounds.width-15)/4,120); //use height whatever you wants.
}
Run Code Online (Sandbox Code Playgroud)
第3步:转到您拥有CollectionView的XIB或StoryBoard.
第4步:在您拥有CollectionView的XIB或StoryBoard中,单击CollectionView.
步骤5:转到InterfaceBuilder,然后在第二个选项卡(即:Size Inspector)中设置Min Spacing
对于Cells = 5
对于Lines = 5
那个.
注意:
- 如果您想在cell = 5之间建立间距,则可以使用此解决方案.
- 如果您的间距不同于5,那么您需要在委托方法中更改值15.
- 例如:单元格之间的间距= 10,然后将代理15更改为10x3 = 30
return CGSizeMake((UIScreen.mainScreen().bounds.width-30)/4,120);
For Cells = 10
For Lines = 10
反之亦然.
Swift 3版
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width
return CGSize(width: (width - 10)/3, height: (width - 10)/3) // width & height are the same to make a square cell
}
Run Code Online (Sandbox Code Playgroud)
小智 14
有一个稍微灵活的答案
允许您调整列数和间距,扩展Zaid Pathan的答案
// MARK: UICollectionViewDelegateFlowLayout delegate method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
let cellSpacing = CGFloat(2) //Define the space between each cell
let leftRightMargin = CGFloat(20) //If defined in Interface Builder for "Section Insets"
let numColumns = CGFloat(3) //The total number of columns you want
let totalCellSpace = cellSpacing * (numColumns - 1)
let screenWidth = UIScreen.mainScreen().bounds.width
let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns
let height = CGFloat(110) //whatever height you want
return CGSizeMake(width, height);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14555 次 |
| 最近记录: |