Как центрировать заголовки разделов UITableView
Я хочу сосредоточить заголовок на представлении таблицы, однако у меня есть 2 проблемы. Во-первых, у меня нет правильной высоты, а во-вторых, UILabel не похож на заголовок по умолчанию - шрифт/размер шрифта/цвет и т.д.... Есть ли лучший способ сосредоточить его и/или есть способ сделать он выглядит как заголовок по умолчанию.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section
{
//section text as a label
UILabel *lbl = [[UILabel alloc] init];
lbl.textAlignment = UITextAlignmentCenter;
lbl.text = @"Header";
[lbl setBackgroundColor:[UIColor clearColor]];
return lbl;
}
Ответы
Ответ 1
Вы также должны реализовать tableView: heightForHeaderInSection, чтобы настроить высоту заголовка:
В справочном документе протокола UITableViewDelegate вы найдете:
Tableview: viewForHeaderInSection:
Обсуждение
Возвращенный объект, например, может быть объектом UILabel или UIImageView. Вид таблицы автоматически настраивается высота заголовка секции до разместить возвращаемый объект просмотра. Этот метод работает корректно только тогда, когда tableView: heightForHeaderInSection: есть также реализовано.
Для центрирования метки заголовка вы должны указать рамку метки перед установкой ее выравнивания в центр.
Для получения стандартного шрифта используйте SystemFontOfSize:
Также остерегайтесь , вы создаете утечку памяти, вы должны вернуть автореализованный вид
Попробуйте что-то вроде этого:
UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease];
lbl.textAlignment = UITextAlignmentCenter;
lbl.font = [UIFont systemFontOfSize:12];
Надеюсь, это поможет,
Винсент
Ответ 2
это должно решить вашу проблему. Протестировано в xcode 6/ios8
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextAlignment:NSTextAlignmentCenter];
return [sectionTitles objectAtIndex:section];
}
Ответ 3
Если вы нацелились на iOS6 и более поздние, вам не нужно предоставлять свой собственный заголовок, если хотите просто сосредоточить заголовок заголовка.
Просто выполните
- tableView: willDisplayHeaderView: forSection:
и установите для свойства textAligment метки:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *) view;
tableViewHeaderFooterView.textLabel.textAlignment = NSTextAlignmentCenter;
}
}
Ответ 4
Ответ Volker в Swift:
Если вы настроите таргетинг на iOS6, и позже вам не нужно предоставлять свой собственный заголовок, если вы просто хотите центрировать заголовок заголовка.
Просто реализуйте
- tableView:willDisplayHeaderView:forSection:
и установите для свойства textAligment метки:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.textAlignment = .Center
}
}
Ответ 5
Здесь моя версия, вам нужно сделать снимок экрана с обычным фоном заголовка и сохранить его 1px широкий фрагмент как "my_head_bg.png" и добавить его в проект. Таким образом, он будет выглядеть ровно в обычном режиме:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UILabel *lbl = [[[UILabel alloc] init] autorelease];
lbl.textAlignment = UITextAlignmentCenter;
lbl.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
lbl.text = @"My Centered Header";
lbl.textColor = [UIColor whiteColor];
lbl.shadowColor = [UIColor grayColor];
lbl.shadowOffset = CGSizeMake(0,1);
lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"my_head_bg"]];
lbl.alpha = 0.9;
return lbl;
}
Ответ 6
Чтобы вызвать этот метод, вы должны сначала реализовать
titleForHeaderInSection
то метод tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
будет называться
Быстрое решение:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.textAlignment = Localize().isRTL ? .Right : .Left
headerView.textLabel?.text = partsDataSource[section]
headerView.textLabel?.textColor = UIColor ( red: 0.0902, green: 0.2745, blue: 0.2745, alpha: 1.0 )
headerView.textLabel?.font = UIFont(name: UIDecorator.sharedInstance.PRIMARY_FONT, size: 14.0)
headerView.contentView.backgroundColor = UIDecorator.sharedInstance.currentTheme.lightShadeColor
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return " "
}
Ответ 7
Попробуйте это
UILabel *tableHeader = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
[tableHeader setText:@"This is header"];
[tableHeader setTextAlignment:UITextAlignmentCenter];
UITableView *newTable = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, 280, 200) style:UITableViewStylePlain];
[newTable setBackgroundColor:[UIColor clearColor]];
[newTable setTableHeaderView:tableHeader];
self.view = newTable;
Ответ 8
В Xamarin:
// Center Header
public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section)
{
if (headerView.GetType() == typeof(UITableViewHeaderFooterView))
{
UITableViewHeaderFooterView tableViewHeaderFooterView = (UITableViewHeaderFooterView)headerView;
tableViewHeaderFooterView.TextLabel.TextAlignment = UITextAlignment.Center;
}
}
Ответ 9
Чтобы изменить высоту, выполните этот метод:
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section {
return 15;
}
Я не уверен в заголовке заголовка по умолчанию - это должно быть проще, чем есть. Возможно, у кого-то есть хорошее фоновое изображение, которое вы можете использовать с белым шрифтом. Но для центрирования, попробуйте следующее:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,15)];
label.textAlignment = UITextAlignmentCenter
label.text = @"Text Should Be Centered";