Настройка раздела заголовка UITableView



Я хочу, чтобы настроить UITableView заголовок для каждого раздела. До сих пор я реализовал



-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section


этой UITabelViewDelegate метод. То, что я хочу сделать, это получить текущий заголовок для каждого раздела и просто добавить UILabel как подвида.



пока я не могу этого сделать. Потому что, я не мог найти ничего, чтобы получить заголовок раздела по умолчанию. Первый вопрос,есть ли способ получить заголовок раздела по умолчанию ?



если это невозможно, мне нужно создать представление контейнера, которое является UIView но на этот раз мне нужно установить цвет фона по умолчанию,цвет тени и т. д. Потому что, если вы внимательно посмотрите в заголовок раздела, он уже настроен.



как я могу получить эти значения по умолчанию для каждого заголовка раздела ?



спасибо всем.

627   20  

20 ответов:

вы можете попробовать это:

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
    /* Create custom view to display section header... */
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
    [label setFont:[UIFont boldSystemFontOfSize:12]];
     NSString *string =[list objectAtIndex:section];
    /* Section header is in 0th index... */
    [label setText:string];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
    return view;
}

выбранный ответ с помощью tableView :viewForHeaderInSection: является правильным.

просто поделиться чаевыми здесь.

Если вы используете storyboard / xib, то вы можете создать еще одну ячейку прототипа и использовать ее для своей "ячейки раздела". Код для настройки заголовка аналогичен тому, как вы настраиваете для ячеек строк.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *HeaderCellIdentifier = @"Header";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier];
    }

    // Configure the cell title etc
    [self configureHeaderCell:cell inSection:section];

    return cell;
}

Swift версия Lochana Tejas ответ:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))
    let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))
    label.font = UIFont.systemFontOfSize(14)
    label.text = list.objectAtIndex(indexPath.row) as! String
    view.addSubview(label)
    view.backgroundColor = UIColor.grayColor() // Set your background color

    return view
}

Если вы используете вид заголовка по умолчанию, вы можете изменить текст на нем только с помощью

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Для Swift:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

Если вы хотите настроить вид, вам нужно создать новый свой собственный.

Почему бы не использовать UITableViewHeaderFooterView?

Если headerInSection не отображается, можно попробовать это.

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}

Это возвращает высоту для заголовка данного раздела.

попробуйте это......

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
{
    // Background view is at index 0, content view at index 1
    if let bgView = view.subviews[0] as? UIView
    {
        // do your stuff
    }

    view.layer.borderColor = UIColor.magentaColor().CGColor
    view.layer.borderWidth = 1
}

Swift 3 версия lochana и estemendoza отвечает:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18))
    let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18))
    label.font = UIFont.systemFont(ofSize: 14)
    label.text = "This is a test";
    view.addSubview(label);
    view.backgroundColor = UIColor.gray;
    return view

}

кроме того, имейте в виду, что вы также должны реализовать:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 100;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //put your values, this is part of my code
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30.0f)];
    [view setBackgroundColor:[UIColor redColor]];
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 150, 20)];
    [lbl setFont:[UIFont systemFontOfSize:18]];
    [lbl setTextColor:[UIColor blueColor]];
    [view addSubview:lbl];

    [lbl setText:[NSString stringWithFormat:@"Section: %ld",(long)section]];

    return view;
}

другие ответы делают хорошую работу по воссозданию представления заголовка по умолчанию, но на самом деле не отвечают на ваш главный вопрос:

есть ли способ получить заголовок раздела по умолчанию ?

есть способ - просто реализовать tableView:willDisplayHeaderView:forSection: в свой делегат. Представление заголовка по умолчанию будет передано во второй параметр, и оттуда вы можете привести его к UITableViewHeaderFooterView а затем добавить / изменить подвиды, как вы хотите.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;

    // Do whatever with the header view...
}

на вашем месте, я бы сделал метод, который возвращает UIView заданный NSString содержать. Например

+ (UIView *) sectionViewWithTitle:(NSString *)title;

в реализации этого метода создайте UIView, добавьте к нему UILabel со свойствами, которые вы хотите установить, и, конечно же, установите его заголовок на данный.

Это самое простое решение. Следующий код можно использовать непосредственно для создания пользовательского заголовка раздела.

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SectionHeaderTableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:@"sectionHeader"];

    //For creating a drop menu of rows from the section
    //==THIS IS JUST AN EXAMPLE. YOU CAN REMOVE THIS IF-ELSE.==
    if (![self.sectionCollapsedArray[section] boolValue])
    {
        headerView.imageView.image = [UIImage imageNamed:@"up_icon"];
    }
    else
    {
        headerView.imageView.image = [UIImage imageNamed:@"drop_icon"];
    }

    //For button action inside the custom cell
    headerView.dropButton.tag = section;
    [headerView.dropButton addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];

    //For removing long touch gestures.
    for (UIGestureRecognizer *recognizer in headerView.contentView.gestureRecognizers)
    {
        [headerView.contentView removeGestureRecognizer:recognizer];
        [headerView removeGestureRecognizer:recognizer];
    }

    return headerView.contentView;
}

Примечание: SectionHeaderTableViewCell-это пользовательский UITableViewCell, созданный в раскадровке.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if([view isKindOfClass:[UITableViewHeaderFooterView class]]){

        UITableViewHeaderFooterView *headerView = view;

        [[headerView textLabel] setTextColor:[UIColor colorWithHexString:@"666666"]];
        [[headerView textLabel] setFont:[UIFont fontWithName:@"fontname" size:10]];
    }
}

Если вы хотите изменить шрифт textLabel в заголовке раздела, вы хотите сделать это в willDisplayHeaderView. Чтобы установить текст, вы можете сделать это в viewForHeaderInSection или titleForHeaderInSection. Удачи вам!

волшебным образом добавить заголовок представления таблицы в swift

недавно я попробовал это.

Мне нужен был один и только один заголовок во всем UITableView.

Как я хотел UIImageView на верхней части TableView. Поэтому я добавил UIImageView поверх UITableViewCell и автоматически он был добавлен в качестве tableViewHeader. Теперь я подключаю ImageView к ViewController и добавил изображение.

Я был смущен, потому что я сделал что-то вроде это в первый раз. Поэтому, чтобы очистить мою путаницу, откройте xml-формат MainStoryBoard и обнаружил, что представление изображения было добавлено в качестве заголовка.

Это сработало для меня. Спасибо xCode и swift.

@ samwize решение в Swift (так upvote его!). Блестящий, используя тот же механизм рециркуляции также для верхних/нижних разделов:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let settingsHeaderSectionCell:SettingsHeaderSectionCell = self.dequeueReusableCell(withIdentifier: "SettingsHeaderSectionCell") as! SettingsHeaderSectionCell

    return settingsHeaderSectionCell
}

кроме titleForHeaderInSection, вы можете просто изменить вид верхнего и нижнего колонтитулов. проверьте мой комментарий здесь: изменить UITable раздел backgroundColor без потери заголовка раздела

Если вы просто хотите добавить заголовок в заголовок tableView, не добавляйте представление. В swift 3.X код выглядит так:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    var lblStr = ""
    if section == 0 {
        lblStr = "Some String 1"
    }
    else if section == 1{
        lblStr = "Some String 2"
    }
    else{
        lblStr = "Some String 3"
    }
    return lblStr
}

вы можете реализовать массив для извлечения заголовка для заголовков.

возвращаясь к исходному вопросу (4 года спустя), вместо того, чтобы перестраивать свой собственный заголовок раздела, iOS может просто позвонить вам (с willDisplayHeaderView:forSection:) сразу после того, как он будет построен по умолчанию. Например, я хотел добавить кнопку графика на правом краю заголовка раздела:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView * header = (UITableViewHeaderFooterView *) view;
    if (header.contentView.subviews.count >  0) return; //in case of reuse
    CGFloat rightEdge = CGRectGetMaxX(header.contentView.bounds);
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(rightEdge - 44, 0, 44, CGRectGetMaxY(header.contentView.bounds))];
    [button setBackgroundImage:[UIImage imageNamed:@"graphIcon"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(graphButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
}

вызовите этот метод делегата

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

return @"Some Title";
}

это даст возможность автоматически добавить заголовок по умолчанию с динамическим название .

вы можете использовать многоразовые и настраиваемый верхний / нижний колонтитул .

https://github.com/sourov2008/UITableViewCustomHeaderFooterSection

использовать tableView: willDisplayHeaderView: чтобы настроить вид, когда он будет отображаться.

это дает вам преимущество в том, что вы можете взять представление, которое уже было создано для представления заголовка, и расширить его, вместо того, чтобы воссоздавать все представление заголовка самостоятельно.

вот пример, который окрашивает раздел заголовка на основе BOOL и добавляет элемент подробного текста в заголовок.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
//    view.tintColor = [UIColor colorWithWhite:0.825 alpha:1.0]; // gray
//    view.tintColor = [UIColor colorWithRed:0.825 green:0.725 blue:0.725 alpha:1.0]; // reddish
//    view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; // pink

    // Conditionally tint the header view
    BOOL isMyThingOnOrOff = [self isMyThingOnOrOff];

    if (isMyThingOnOrOff) {
        view.tintColor = [UIColor colorWithRed:0.725 green:0.925 blue:0.725 alpha:1.0];
    } else {
        view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0];
    }

    /* Add a detail text label (which has its own view to the section header… */
    CGFloat xOrigin = 100; // arbitrary
    CGFloat hInset = 20;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin + hInset, 5, tableView.frame.size.width - xOrigin - (hInset * 2), 22)];

    label.textAlignment = NSTextAlignmentRight;

    [label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]
    label.text = @"Hi.  I'm the detail text";

    [view addSubview:label];
}

Comments

    Ничего не найдено.