UITableView 美化- 增加一个好看的背景


给UITableView增加一个好看的背景能为应用程序增色不少,并能促进app的销售,但是随便增加一个背景图片会史你的app更加丑陋。

  1. //This method produces odd artifacts in the background image:   
  2. ATableViewController *yourTableViewController = [[ATableViewController alloc] initWithStyle:UITableViewStyleGrouped];  
  3. yourTableViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TableViewBackground.png"]];  
这种方法直接设置tableview的背景色,效果不佳。

正确的方式:在tableview后面放置一个背景视图,并将tableview设为透明色。

  1. UIView *backgroundView = [[UIView alloc] initWithFrame: window.frame];  
  2. backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TableViewBackground.png"]];  
  3. [window addSubview:backgroundView];  
  4.   
  5. yourTableViewController = [[ATableViewController alloc] initWithStyle:UITableViewStyleGrouped];  
  6. yourTableViewController.view.backgroundColor = [UIColor clearColor];  
  7. [window addSubview:yourTableViewController.view];  
在用代码产生的tableViewcontroller中,可以通过loadview方法设置
  1. - (void)loadView {   
  2.     [super loadView];   
  3.     UIImageView *v = [[[UIImageView alloc] initWithFrame:self.view.bounds] autorelease];   
  4.     [v setImage:[UIImage imageNamed:@"table_background.png"]];   
  5.     [self.view addSubview:v];   
  6.    
  7.    
  8.     self.tableView = [[[UIView alloc] initWithFrame:self.view.bounds] autorelease];   
  9.     [self.tableView setBackgroundColor:[UIColor clearColor]];   
  10.     [self.view addSubview:self.tableView];   
  11. }   

在用nib初始化的tableViewcontroller中,可以的在初始化实例前设置

  1. // create the view controller from your nib   
  2. MyViewController *vc = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];  
  3. vc.tableView.backgroundColor = [UIColor clearColor];  
  4.   
  5. // create the background   
  6. UIImageView *iv = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"background.png"]];  
  7. iv.contentMode = UIViewContentModeCenter;  
  8. iv.userInteractionEnabled = TRUE;  
  9.   
  10. [navigationController pushViewController:vc animated:YES];  
  11.   
  12. // put the background behind the tableview   
  13. [vc.tableView.superview addSubview:iv];  
  14. [iv addSubview:vc.tableView];  
  15.   
  16. // don't forget to release your view controller & image view!   
  17. [vc release];  
  18. [iv release];  

相关内容