您的位置:首页 > Web前端 > CSS

cell的背景渐变色和修改样式

2016-01-08 17:28 489 查看
有些时候我们要修改cell 的背景色 或者 cell 上面 可能会加个边框等等其他的

例如:



或许更加复杂的页面。

这个如果放在以前我可能会 用一个 baseView 用这个baseView 改变样式,这种方式可是可以,但是不好。如果我们现在需要一个色值渐变的cell 等等。

下面我介绍一个比较好的处理方法

1.渐变色值

void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef endColor) {

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };

NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];

//渐变属性
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);

//渐变的开始点和结束点
CGPoint startPoint = CGPointMake(rect.size.width/2.0, 0);
CGPoint endPoint = CGPointMake(rect.size.width/2.0,rect.size.height);

CGContextSaveGState(context);//保存context状态
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);//还原context的状态 这样的话,在这个方法里面的对context的操作不会影响 其他context 的操作

//含有create 、copy、retain 创建的都需要师傅
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}


2.修改cell的边框

我们自定义一个CustomCellBackground 视图

重写 -(void) drawRect: (CGRect) rect

-(void) drawRect: (CGRect) rect
{
CGContextRef context = UIGraphicsGetCurrentContext();

UIColor * whiteColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
UIColor * lightGrayColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0];
//lightGrayColor = [UIColor blueColor];

drawLinearGradient(context, rect, whiteColor.CGColor, lightGrayColor.CGColor);

UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
CGRect strokeRect = CGRectInset(rect, 5.0, 5.0);
[redColor setStroke];
//[[UIColor blueColor] setFill];
//CGContextSetStrokeColorWithColor(context, redColor.CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextStrokeRect(context, strokeRect);
//CGContextFillRect(context, strokeRect);

}


3.然后在tableView上显示

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
if (![cell.backgroundView isKindOfClass:[CustomCellBackground class]]) {
cell.backgroundView = [[CustomCellBackground alloc] init];
}

if (![cell.selectedBackgroundView isKindOfClass:[CustomCellBackground class]]) {
cell.selectedBackgroundView = [[CustomCellBackground alloc] init];
}

}

//这里一定要重绘 否则会出现显示问题
[cell.backgroundView setNeedsDisplay];
[cell.selectedBackgroundView setNeedsDisplay];

cell.textLabel.text = _dataArr[indexPath.row];
return cell;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: