Как программно настроить заголовок раздела UITableView (iPhone/iPad)?
Я создал UITableView
в построителе интерфейсов с помощью storyboards
. UITableView
устанавливается с помощью static cells
и нескольких различных разделов.
Проблема, с которой я сталкиваюсь, заключается в том, что я пытаюсь настроить приложение на нескольких разных языках. Для этого мне нужно как-то изменить названия разделов UITableView
.
Пожалуйста, кто-нибудь может мне помочь? В идеале я хотел бы подойти к проблеме с помощью IBOutlets
, но я подозреваю, что в этом случае это даже невозможно. Любые советы и предложения будут действительно оценены.
Спасибо заранее.
Ответы
Ответ 1
Как только вы подключите UITableView delegate
и datasource
к контроллеру, вы можете сделать что-то вроде этого:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *sectionName;
switch (section)
{
case 0:
sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
break;
case 1:
sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
break;
// ...
default:
sectionName = @"";
break;
}
return sectionName;
}
Ответ 2
Если вы пишете код в Swift, это будет выглядеть как пример
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
switch section
{
case 0:
return "Apple Devices"
case 1:
return "Samsung Devices"
default:
return "Other Devices"
}
}
Ответ 3
Использовать метод UITableViewDataSource
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
Ответ 4
titleForHeaderInSection - это метод делегатов UITableView, поэтому для применения заголовка текста раздела пишите следующим образом:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"Hello World";
}
Ответ 5
Обратите внимание, что -(NSString *)tableView:
titleForHeaderInSection:
не вызывается UITableView, если - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
реализуется в делегате UITableView;
Ответ 6
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 45.0f;
//set height according to row or section , whatever you want to do!
}
указан текст метки раздела.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeaderView;
sectionHeaderView = [[UIView alloc] initWithFrame:
CGRectMake(0, 0, tableView.frame.size.width, 120.0)];
sectionHeaderView.backgroundColor = kColor(61, 201, 247);
UILabel *headerLabel = [[UILabel alloc] initWithFrame:
CGRectMake(sectionHeaderView.frame.origin.x,sectionHeaderView.frame.origin.y - 44, sectionHeaderView.frame.size.width, sectionHeaderView.frame.size.height)];
headerLabel.backgroundColor = [UIColor clearColor];
[headerLabel setTextColor:kColor(255, 255, 255)];
headerLabel.textAlignment = NSTextAlignmentCenter;
[headerLabel setFont:kFont(20)];
[sectionHeaderView addSubview:headerLabel];
switch (section) {
case 0:
headerLabel.text = @"Section 1";
return sectionHeaderView;
break;
case 1:
headerLabel.text = @"Section 2";
return sectionHeaderView;
break;
case 2:
headerLabel.text = @"Section 3";
return sectionHeaderView;
break;
default:
break;
}
return sectionHeaderView;
}
Ответ 7
Я не знаю прошлых версий протоколов UITableView
, но с iOS 9, func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
является частью протокола UITableViewDataSource
.
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section name"
}
}
Вам не нужно объявлять delegate
для заполнения таблицы данными.
Ответ 8
Swift 3:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionsTitlesKeys = ["Main","New","Options"]
let key = sectionsTitlesKeys[section]
let localizedString = NSLocalizedString(key,tableName: nil, bundle: Bundle.main, value: "", comment: "")
return sectionsTitles[section]
}
Ответ 9
У меня было аналогичное требование. У меня была статическая таблица со статическими ячейками в моей Main.storyboard(Base). Локализовать заголовки разделов с использованием файлов .string, например. Main.strings(немецкий) просто выберите раздел в раскадровке и обратите внимание на идентификатор объекта
![ИД объекта]()
Затем перейдите в строковый файл, в моем случае Main.strings(немецкий) и вставьте перевод, например:
"MLo-jM-tSN.headerTitle" = "Localized section title";