iOS UICollectionView中添加边框

DaimerIP属地: 浙江
0.083字数 361

摘要:如果用layer.border来设置九宫格,当你设置宽度为0.5,两个cell挨在一块,会使他们的边框宽度增加一倍,如果在自定义的cell中代码加上view,也会引起上下左右的view因cell所处的方位的不同从而位置不同而引起麻烦。而且还会因为cell的重用而引起一些错误,所以查阅了部分资料总结了以下方法我用的是自定义一个cell的方法用枚举方法来表示边框的方位//MyCell.mtypedefenum:NSUInteger{SYCellBorderDirectionTop

如果用layer.border来设置九宫格,当你设置宽度为0.5,两个cell挨在一块,会使他们的边框宽度增加一倍,如果在自定义的cell中代码加上view,也会引起上下左右的view因cell所处的方位的不同从而位置不同而引起麻烦。而且还会因为cell的重用而引起一些错误,
所以查阅了部分资料总结了以下方法
我用的是自定义一个cell的方法
用枚举方法来表示边框的方位

//MyCell.m
typedef enum : NSUInteger {
SYCellBorderDirectionTop = 1 << 0,
SYCellBorderDirectionBottom = 1<<1,
SYCellBorderDirectionRight = 1 <<2,
SYCellBorderDirectionLeft = 1<<3,

} SYCellBorderDirection;

下面就是如何,在各个方位来添加border

//MyCell.m
-(void)setBorderWithDirection:(SYCellBorderDirection)direction{
CAShapeLayer *layer = [[CAShapeLayer alloc]init];
layer.lineWidth = 0.5;
layer.borderWidth =0.5;
CGRect rect = self.contentView.bounds;
layer.strokeColor = [UIColor colorWithRed:224.0/255.0 green:224.0/255.0 blue:224.0/255.0 alpha:1].CGColor;


UIBezierPath*path = [[UIBezierPath alloc]init];

// SYCellBorderDirection *dir = SYCellBorderDirectionTop|SYCellBorderDirectionBottom|SYCellBorderDirectionRight|SYCellBorderDirectionLeft
if (direction &; SYCellBorderDirectionTop) {
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(rect.size.width, 0)];

layer.path = path.CGPath;

[self.contentView.layer addSublayer:layer];

}
if (direction &; SYCellBorderDirectionBottom) {
[path moveToPoint:CGPointMake(0, rect.size.height)];

[path addLineToPoint:CGPointMake(rect.size.width, rect.size.height)];

layer.path = path.CGPath;

[self.contentView.layer addSublayer:layer];

}
if (direction &; SYCellBorderDirectionRight) {
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(0, rect.size.height)];

layer.path = path.CGPath;

[self.contentView.layer addSublayer:layer];

}
if (direction &; SYCellBorderDirectionLeft) {
[path moveToPoint:CGPointMake(rect.size.width, 0)];
[path addLineToPoint:CGPointMake(rect.size.width, rect.size.height)];

layer.path = path.CGPath;

[self.contentView.layer addSublayer:layer];

}

}

最后我们就可以因为位置的不同来设置边框
在MyColleViewController.m里给位置不同的cell的tag赋值

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
...
cell.tag = indexPath.row;
...
}

然后cell根据tag的不同来添加边框

//MyCell.m
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
if ((self.tag/3)==0) {
[self setBorderWithDirection:SYCellBorderDirectionBottom|SYCellBorderDirectionRight|SYCellBorderDirectionTop];
}if ((self.tag/3)>0) {
[self setBorderWithDirection:SYCellBorderDirectionBottom|SYCellBorderDirectionRight];
}
} 
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
1人点赞
Daimer其实并不难,是你太悲观!
总资产21共写了6.5W字获得197个赞共82个粉丝

推荐阅读更多精彩内容