zoukankan      html  css  js  c++  java
  • ios开发――解决UICollectionView的cell间距与设置不符问题

    在用UICollectionView展示数据时,有时我们希望将cell的间距调成一个我们想要的值,然后查API可以看到有这么一个属性:

    - (CGFloat)minimumInteritemSpacing {    return 0;}

    然而很多情况下我们会发现,这样写不能满足我们的要求,cell之间仍然有一个不知道怎么产生的间距。

    我们知道cell的间距是由cell的大小itemSize和section的缩进sectionInset共同决定的,通过这两个数据,UICollectionView动态地将cell放在相应的位置,然而即使我们接着调用inset方法也没有用。

    - (UIEdgeInsets)sectionInset{    return UIEdgeInsetsMake(0, 0, 0, 0);}

    <注:我想实现的是0间距,其他情况类似>

    可以看到,继承UICollectionViewFlowLayout后在- layoutAttributesForElementsInRect:方法中打印一下这些cell的frame的结果

    -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{    NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];        for (UICollectionViewLayoutAttributes *attr in attributes) {        NSLog(@"%@", NSStringFromCGRect([attr frame]));    }}

    /

    从上面两行就可以看出来,我的高度是42.8,然而两个cell的x值间距却为46,也就是说有大约3px的间距。

    其实,正如minimumInteritemSpacing的名字一样,这个属性设置的是间距的最小值,那么,我们实际需要的应该是一个"maximumInteritemSpacing",也就是最大间距。要解决这个问题,需要自己做一些计算。

    依旧是继承UICollectionViewFlowLayout,然后在- layoutAttributesForElementsInRect:方法中添加如下代码:

    //从第二个循环到最后一个    for(int i = 1; i < [attributes count]; ++i) {        //当前attributes        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];        //上一个attributes        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];        //我们想设置的最大间距,可根据需要改        NSInteger maximumSpacing = 0;        //前一个cell的最右边        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);        //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置        //不加这个判断的后果是,UICollectionView只显示一行,原因是下面所有cell的x值都被加到第一行最后一个元素的后面了        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {            CGRect frame = currentLayoutAttributes.frame;            frame.origin.x = origin + maximumSpacing;            currentLayoutAttributes.frame = frame;        }    }

    原因注释中已经解释得非常详细了。这样就可以解决cell的间距问题了。再次运行,效果非常好:

  • 相关阅读:
    sourceTree和eclipse 的使用
    oracle习题练习
    oracle详解
    单例模式
    反射详解
    Oracle 存储过程判断语句正确写法和时间查询方法
    MVC4 Jqgrid设计与实现
    遇到不支持的 Oracle 数据类型 USERDEFINED
    ArcGIS Server10.1 动态图层服务
    VS2010连接Oracle配置
  • 原文地址:https://www.cnblogs.com/itlover2013/p/4446124.html
Copyright © 2011-2022 走看看