Скрыть разделы Static TableView
Я нашел этот урок, который скрывает раздел Static TableView: http://code-ninja.org/blog/2012/02/29/ios-quick-tip-programmatically-hiding-sections-of-a-uitableview-with-static-cells/
Он отлично работает, но только без его модификации, если я добавляю раздел или строку, он работает плохо. Я новичок, и я не могу его изменить, может ли кто-нибудь помочь мне скрыть несколько разделов?
Большое вам спасибо!
Ответы
Ответ 1
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section == 2 && _hideTableSection) {
//header height for selected section
return 0.1;
} else {
//keeps all other Headers unaltered
return [super tableView:tableView heightForHeaderInSection:section];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
if (section == 2 && _hideTableSection) {
//header height for selected section
return 0.1;
} else {
// keeps all other footers unaltered
return [super tableView:tableView heightForFooterInSection:section];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 1) { //Index number of interested section
if (hideTableSection) {
return 0; //number of row in section when you click on hide
} else {
return 2; //number of row in section when you click on show (if it higher than rows in Storyboard, app will crash)
}
} else {
return [super tableView:tableView numberOfRowsInSection:section]; //keeps inalterate all other rows
}
}
Ответ 2
Я хотел поделиться некоторым кодом, который я написал, чтобы решить эту проблему после того, как выкапывал множество ответов и натыкался на многие глюки. Это для xCode 7.2.1. (Примеры кода в Swift)
Мой вариант использования заключался в том, что я хотел использовать легкость разбиения на таблицы с разбивкой по страницам, но мне нужно было скрыть определенные разделы на основе профилей пользователей. Чтобы выполнить эту работу (как описано в других сообщениях), мне нужно скрыть верхние и нижние колонтитулы, строки в разделе И скрыть текст заголовка/нижнего колонтитула (по крайней мере, в верхней части). Я обнаружил, что если бы я не скрывал (делал прозрачным) текст, тогда пользователь мог прокручивать верхнюю часть таблицы (под навигационным контроллером) и видеть, что текст переполнен.
Я хотел сделать это легко модифицировать и не хотел, чтобы условия распространялись по всему моему коду, поэтому я создал одну функцию, называемую shouldHideSection (section: Int), которая является единственной функцией, которую я должен изменить, чтобы изменить, какие строки скрыт.
func shouldHideSection(section: Int) -> Bool {
switch section {
case 0: // Hide this section based on condition below
return user!.isProvider() ? false : true
case 2:
return someLogicForHiddingSectionThree() ? false : true
default:
return false
}
}
Теперь оставшаяся часть кода вызывает вызовыHideSection().
// Hide Header(s)
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return shouldHideSection(section) ? 0.1 : super.tableView(tableView, heightForHeaderInSection: section)
}
// Hide footer(s)
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return shouldHideSection(section) ? 0.1 : super.tableView(tableView, heightForFooterInSection: section)
}
// Hide rows in hidden sections
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return shouldHideSection(indexPath.section) ? 0 : super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
// Hide header text by making clear
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if shouldHideSection(section) {
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.clearColor()
}
}
// Hide footer text by making clear
override func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
if shouldHideSection(section) {
let footerView = view as! UITableViewHeaderFooterView
footerView.textLabel!.textColor = UIColor.clearColor()
}
}
Мне пришлось экспериментировать со многими разными значениями (возвращающими 0, 0,1, -1,...), чтобы наконец получить удовлетворительное решение (по крайней мере, на iOS 9.x).
Я надеюсь, что это полезно, сообщите мне, если вы предложили улучшения.
Ответ 3
Если вы вернете 0 для высоты раздела, Apple API проигнорирует его. Поэтому просто верните небольшое значение больше 0.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section == 0) {
return 1;
}
return 44;
}
Также реализуйте представление для заголовка и возврата nil для раздела, который вы не хотите показывать.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (section == 0 && !self.personaCells.count) {
return nil;
}
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, headerView.frame.size.width, 20)];
NSString *headerTitle = @"SAMPLE TITLE";
headerLabel.text = headerTitle;
[headerView addSubview:headerLabel];
return headerView;
}
Ответ 4
Для Swift 3
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 2 && hideTableSection {
//header height for selected section
return 0.1
}
//keeps all other Headers unaltered
return super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 && hideTableSection {
//header height for selected section
return 0.1
}
return super.tableView(tableView, heightForFooterInSection: section)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 { //Index number of interested section
if hideTableSection {
return 0 //number of row in section when you click on hide
} else {
return 2 //number of row in section when you click on show (if it higher than rows in Storyboard, app will crash)
}
} else {
return super.tableView(tableView, numberOfRowsInSection: section) //keeps inalterate all other rows
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 2 && hideTableSection {
return ""
}
return super.tableView(tableView, titleForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 2 && hideTableSection {
return ""
}
return super.tableView(tableView, titleForFooterInSection: section)
}
Ответ 5
Задайте значение раздела равным 0,01. В любом разделе, который вы хотели скрыть, вы можете попробовать следующим образом: -
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
CGFloat headerHeight=10.f;
if (section==0)
{
headerHeight=0.01f;
}
else
{
headerHeight=50.0f;
}
return headerHeight;
}
Ответ 6
если вы удалите заголовок заголовка раздела из раскадровки, он автоматически исчезнет. Под этим я подразумеваю не только заголовок, но и пространство, взятое им.