Подтвердить что ты не робот

Как реализовать `viewForHeaderInSection` в стиле iOS7?

Как реализовать (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section в стиле iOS7, например (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section?

P.S. Мне просто нужно изменить цвет заголовка заголовка UITableView и сохранить его.

4b9b3361

Ответ 1

Вы можете изменить цвет метки внутри стандартного заголовка таблицы до рендеринга с помощью willDisplayHeaderView. Будет также работать как для iOS6/iOS7.

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

        UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *) view;
        tableViewHeaderFooterView.textLabel.textColor = [UIColor blueColor];
    }
}

Для справки

UITableViewHeaderFooterView: https://developer.apple.com/documentation/uikit/uitableviewheaderfooterview

Протокол UITableViewDelegate: https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614905-tableview

Ответ 2

Если вам нужно изменить глобальный цвет для верхнего и нижнего колонтитула, используйте appearance:

[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextColor:[UIColor redColor]];

Ответ 3

В начале жизненного цикла контроллера (например, -viewDidLoad) зарегистрируйте класс:

 [[self tableView] registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"headerFooterReuseIdentifier"];

Затем в вашем методе: (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section удалите ячейку, создайте ее, как хотите, и верните ее:

 UIColor *titleColor = ... // Your color here.
 UITableViewHeaderFooterView *headerFoorterView = [[self tableView] dequeueReusableHeaderFooterViewWithIdentifier:@"headerFooterReuseIdentifier"];
 [[headerFooterView textLabel] setTextColor:titleColor];
 return headerFooterView;

И как вы используете реализацию по умолчанию.

Ответ 4

Не идеально, но решение:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    if (<is_iOS7>) {
        label.text = [[NSString stringWithFormat:@"  %@", <title>] uppercaseString];
    } else {
        if (<is_iPad>) {
            label.text = [NSString stringWithFormat:@"          %@", <title>];
        } else {
            label.text = [NSString stringWithFormat:@"  %@", <title>];
        }
    }
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 38.f;
}

Ответ 5

И ответ @aumansoftware - также лучший способ добавить контент в стандартный заголовок, например, кнопку. Вот пример в Swift:

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if (view.isKindOfClass(UITableViewHeaderFooterView)) {
        let headerView = view as UITableViewHeaderFooterView

        // Label
        headerView.textLabel.textColor = UIColor.blueColor()

        // New Button
        let addPeopleButton: UIButton = UIButton.buttonWithType(.ContactAdd) as UIButton
        addPeopleButton.addTarget(self, action: "showPeoplePicker:", forControlEvents: UIControlEvents.TouchUpInside)

        addPeopleButton.setTranslatesAutoresizingMaskIntoConstraints(false)
        headerView.addSubview(addPeopleButton)
        let right: NSLayoutConstraint = NSLayoutConstraint(item: addPeopleButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -12)
        let vertical: NSLayoutConstraint = NSLayoutConstraint(item: addPeopleButton, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
        headerView.addConstraints([right, vertical])
    }
}

Ответ 6

Он работает точно так же, как и в iOS 6. Создайте представление (или просто ярлык, который охватывает весь заголовок) и настройте его в соответствии с вашими требованиями.