2014-01-21 24 views
5

UITableView使用UISearchBar報告比預期更大的contentSize。使用零單元格時,預期的內容高度將爲零。相反,下面的代碼在iPhone 4英寸運行iOS 7.使用UISearchBar時UITableView contentSize錯誤

@implementation HPViewController { 
    UITableView *_tableView; 
    UISearchBar *_searchBar; 
    UISearchDisplayController *_searchController; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    [self.view addSubview:_tableView]; 

    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 

    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self]; 
    _searchController.delegate = self; 
    _searchController.searchResultsDataSource = self; 
    _tableView.tableHeaderView = _searchBar; 
} 

- (void)viewDidLayoutSubviews 
{ 
    CGSize contentSize = _tableView.contentSize; 
    NSLog(@"%f", contentSize.height); // 612.000000 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 0; } 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { return nil; }; 

@end 

輸出612在評論,設置頭部視圖使得代碼輸出0,如所預期的行。

此外,如果我將空的UIView指定爲標頭,那麼contentSize將是正確的並且與標頭的高度相匹配。該問題只發生在UISearchBar

有沒有辦法解決這個問題?難道我做錯了什麼?

+1

我今天遇到與iOS 11.2相同的問題。表中有1個標題和1個單元格,我幾乎可以將所有內容從屏幕上滾動出來。不過,contentSize具有我期待的iOS 10.3.1的高度。 –

回答

2

UISearchBar放在容器內UIView主要解決了問題。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    [self.view addSubview:_tableView]; 

    UIView *searchBarContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
    _searchBar = [[UISearchBar alloc] initWithFrame:searchBarContainer.bounds]; 
    [searchBarContainer addSubview:_searchBar]; 

    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self]; 
    _searchController.delegate = self; 
    _searchController.searchResultsDataSource = self; 
    _tableView.tableHeaderView = searchBarContainer; 
} 

不幸的是UISearchBar在我還無法分離的情況下出現了一些故障。我選擇通過添加所有單元格的高度來手動計算contentSize

+0

感謝您添加到子視圖的提示。至少對我來說,這是自己的工作。 –

+0

當搜索欄自動隱藏在導航欄中時有一個功能。不幸的是,它消失了這個視圖容器的bcs ... –

0

因爲沒有細胞顯示添加此委託方法

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section 
{ 
    return [[UIView alloc] initWithFrame:CGRectZero]; 
} 

也許您的頁腳視圖groing起來。

+0

那不會被調用。我的示例代碼中沒有部分。標題是表格視圖標題,而不是節標題。 – hpique

+0

是的,你是對的。所以我沒有理想。它非常受歡迎。 –

相關問題