我们可以通过[cell setBackgroundView:[[UIImageView alloc] initWithImage:@"xxx"]];方法设置背景,假设有一张图片名称为cell_background.png,我们用它作为cell背景图片,
//前面是一张图片,不信你拖动鼠标看看
直接使用[cell setBackgroundView:[[UIImageView alloc] initWithImage:@"cell_background"]], 那么显示的时候是比较奇怪的样子,代码如下,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
//关键代码
cell.backgroundColor = [UIColor clearColor];
UIImage *cellBackImage = [UIImage imageNamed:@"cell_background"];
[cell setBackgroundView:[[UIImageView alloc] initWithImage:cellBackImage]];
//....
}
效果如下图,
图片因为拉伸,边缘都模糊了,这不是我们想要的结果和效果。
我们使用UIImage对象的方法,来保持边缘地方不变,而只是拉伸中间的区域,这样图片就不会模糊了,修改的代码如下,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//..
cell.backgroundColor = [UIColor clearColor];
UIImage *cellBackImage = [UIImage imageNamed:@"cell_background"];
//这里是关键代码
cellBackImage = [cellBackImage resizableImageWithCapInsets:UIEdgeInsetsMake(15, 320, 14, 0)];//(top,left,bottom,right)
[cell setBackgroundView:[[UIImageView alloc] initWithImage:cellBackImage]];
//...
}
我们看一下resizableImageWithCapInsets方法以及它的参数UIEdgeInset
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0); // create a resizable version of this image. the interior is tiled when drawn.
UIKIT_STATIC_INLINE UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {
UIEdgeInsets insets = {top, left, bottom, right};
return insets;
}
这个就是设置要保留的边缘,这样更改代码以后,我们的效果图如下,
这样就显得正常了,看起来也舒服多了吧?
PS:最近在看一些完整的开源代码,例如Code4app上面的“内涵糗事”,其实看了别人的代码,可以突然有种想通了得感觉。上面的这个例子就是我自己在开源代码上面看见的一个细节,把抽象出来与大家共享。