我想在我的UITableView爲空時顯示圖像背景。 目前我嘗試添加一個UIImageView到我的視圖控制器包含一個表,但XCode不允許它。iPhone UITableView圖像背景當表空時
有沒有一種很好的方法呢?
我想在我的UITableView爲空時顯示圖像背景。 目前我嘗試添加一個UIImageView到我的視圖控制器包含一個表,但XCode不允許它。iPhone UITableView圖像背景當表空時
有沒有一種很好的方法呢?
您可以在表視圖頂部添加圖像視圖或更改表視圖的背景視圖。
// Check if table view has any cells
int sections = [self.tableView numberOfSections];
BOOL hasRows = NO;
for (int i = 0; i < sections; i++) {
BOOL sectionHasRows = ([self.tableView numberOfRowsInSection:i] > 0) ? YES : NO;
if (sectionHasRows) {
hasRows = YES;
break;
}
}
if (sections == 0 || hasRows == NO)
{
UIImage *image = [UIImage imageNamed:@"test.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Add image view on top of table view
[self.tableView addSubview:imageView];
// Set the background view of the table view
self.tableView.backgroundView = imageView;
}
UITableView
有一個backgroundView
屬性。將此屬性設置爲包含背景圖像的UIImageView
。
請注意,我不希望顯示爲UITableView的任何背景。我只想在表格沒有顯示單元時顯示一些背景。我只是想隱藏表格並改爲放置背景。你的建議會對此有用嗎? – bashan 2012-01-18 21:37:15
在你numberOfRowsInSection方法:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if data.count > 0 {
return data.count
}
else{
let image = UIImage(named: "Nature")
let noDataImage = UIImageView(image: image)
noDataImage.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: tableView.frame.height)
tableView.backgroundView = noDataImage
tableView.separatorStyle = .none
return 0
}
}
numberOfSections應大於0
謝謝,不錯的把戲。順便說一句,我如何可視化地設計一個UIView並將其用作桌面上的圖層?我不再有選擇簡單地使用新的XCode故事板來設計視圖... – bashan 2012-01-18 21:46:04
您可以通過創建一個新的nib文件並將其加載到UIView中來設計視圖。 – simonbs 2012-01-18 21:49:21
我曾經在舊的XCode上做過。故事板附帶的新XCode似乎以不同的方式工作。它不允許您創建新的自定義大小視圖,並且所有視圖都位於同一個故事板文件中。 – bashan 2012-01-19 21:16:57