2012-01-18 54 views

回答

15

您可以在表視圖頂部添加圖像視圖或更改表視圖的背景視圖。

// 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; 
} 
+0

謝謝,不錯的把戲。順便說一句,我如何可視化地設計一個UIView並將其用作桌面上的圖層?我不再有選擇簡單地使用新的XCode故事板來設計視圖... – bashan 2012-01-18 21:46:04

+0

您可以通過創建一個新的nib文件並將其加載到UIView中來設計視圖。 – simonbs 2012-01-18 21:49:21

+0

我曾經在舊的XCode上做過。故事板附帶的新XCode似乎以不同的方式工作。它不允許您創建新的自定義大小視圖,並且所有視圖都位於同一個故事板文件中。 – bashan 2012-01-19 21:16:57

4

UITableView有一個backgroundView屬性。將此屬性設置爲包含背景圖像的UIImageView

+0

請注意,我不希望顯示爲UITableView的任何背景。我只想在表格沒有顯示單元時顯示一些背景。我只是想隱藏表格並改爲放置背景。你的建議會對此有用嗎? – bashan 2012-01-18 21:37:15

0

在你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