简体   繁体   中英

How to add an image subview to a tableview programmatically

I'm new to programming, and I know how to add a static image behind a tableView in a .xib file, but not in code. I have tried the following code:

UIImage * image = [UIImage imageNamed:@"pic.png"];
[self.view addSubView: image];

but nothing happens when I write this!

To display an UIImage you have to use an UIImageView and put it under the UITableView using the same frame. Don't forget to set the table view's background to transparent.

UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]];
iv.frame = CGRectMake(0.0, 0.0, 300.0, 600.0);
UITableView *tv = [[UITableView alloc] initWithFrame:iv.frame style:UITableViewStylePlain];
tv.opaque = NO;
tv.backgroundColor = [UIColor clearColor];
[self.view addSubView: iv];
[self.view addSubView: tv];
[iv release];
[tv release];

You need to use a UIImageView, not a UIImage. Also, when adding a view programmatically, don't forget to set the frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM