UIView UITableView 背景图片添加

时间:2023-03-09 05:22:46
UIView UITableView 背景图片添加

这几天,经常用到为某个视图设置背景图片,而API中UIView没有设置背景图片的方法,搜集归纳如下:

第一种方法:

利用的UIView的设置背景颜色方法,用图片做图案颜色,然后传给背景颜色。

UIColor *bgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bgImg.png"];

UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(,,,)];

[myView setBackGroundColor:bgColor];

第二种方法:

利用UIView的sendSubviewToBack方法

UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(,,,)];

UIImageView *bgImgView = [[UIImageView alloc]initWithFrame:CGRectMake(,,,)];

 [bgImageView setImage:@"bgImg.png"];

 [myView addSubView:bgImgView];

 [myView sendSubviewToBack:bgImgView];

 [bgImgView release];

 [myView release];

第三种方法:

IOS视图都是一个图层,最先放置的视图就会在最底层,如此,最先给一个视图添加一个UIImageView后,然后

在上面再一一添加其他控件,效果也跟背景图片差不多。

----------------------------------------------------------------------------------------------------------------

给UITableView添加背景图呢,可以按照方法:
1 在UITableView控件下面添加一个UIImageView控件,如图1,顺序不可更改,否则会压盖

UIView UITableView 背景图片添加
2 将UITableView的background设置为ClearColor,如图2

UIView UITableView 背景图片添加
3 同样的,将UITableView的父视图的background设置为ClearColor
4 这样背景图就设置好了,我们看一下效果,如图3:

UIView UITableView 背景图片添加
5 可以发现在UITableView的四个转角地方有黑色块,没有完全使用背景图,非常难看,那么如何解决这个问题呢,只要在UITableView所在的ViewController种的viewDidLoad方法种添加下面的代码:

- (void)viewDidLoad {
self.tableView.backgroundColor = [UIColor clearColor]; }

也就是重新把tableView的backgroundColor 设置为clearColor。

谨慎怀疑这时ios的一个bug。

最后的效果如图4:

UIView UITableView 背景图片添加

开发环境为xcode3.2.3 +ios sdk4.0