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

Измените цвет фона заголовков разделов в UITableView, используя массив заголовков

У меня есть массив заголовков, которые я использую

let sectionHeaderTitleArray = ["test1","test2","test3]

и они показаны с использованием

func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
} 

Теперь все это прекрасно работает, но я хотел бы изменить цвет фона заголовков, чтобы они были более заметными (Darker Color)

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

благодаря

Обновить

  //number of sections and names for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sectionHeaderTitleArray.count
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionHeaderTitleArray[section] as String
    }
    func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
        return self.tableView.backgroundColor = UIColor.lightGrayColor()
    }
4b9b3361

Ответ 1

Вместо использования

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

Метод источника данных, вы можете использовать

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

делегировать метод и просто настроить возвращаемый UIView как вы хотите.

Например, установите текст UILabel textLabel в желаемое значение и backgroundColor в желаемый UIColor.

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let returnedView = UIView(frame: CGRectMake(x, y, width, height)) //set these values as necessary
    returnedView.backgroundColor = UIColor.lightGrayColor()

    let label = UILabel(frame: CGRectMake(labelX, labelY, labelWidth, labelHeight))
    label.text = self.sectionHeaderTitleArray[section]
    returnedView.addSubview(label)

    return returnedView
}

SWIFT 5

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let returnedView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) //set these values as necessary
            returnedView.backgroundColor = .white

            let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))

            label.text = self.sectionHeaderTitleArray[section]
            returnedView.addSubview(label)

            return returnedView
        }

Ответ 2

Если вы используете только titleForHeaderInSection:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    (view as! UITableViewHeaderFooterView).backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
}

Ответ 3

Вы должны держать оба

titleForHeaderInSection

А ТАКЖЕ

viewForHeaderInSection

Вот какой рабочий код в Swift 3

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return self.sectionHeaderTitleArray[section]
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25))
    returnedView.backgroundColor = .lightGray

    let label = UILabel(frame: CGRect(x: 10, y: 7, width: view.frame.size.width, height: 25))
    label.text = self.sectionHeaderTitleArray[section]
    label.textColor = .black
    returnedView.addSubview(label)

    return returnedView
}

Ответ 4

SWIFT 4

Супер легко, задав заголовок, цвет фона contentView..

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerId") as! CustomHeader
   header.contentView.backgroundColor = AnyColor
   return header
}

Ответ 5

Swift 4.X

Это проверенный и рабочий код.

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Total Count (41)"
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    view.tintColor = UIColor.lightGray
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.textColor = UIColor.darkGray
    header.textLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
}

Ответ 6

Swift 3+

Я использовал это:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 20))
    headerView.backgroundColor = .lightGray

    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = stringValues[section]
    headerView.addSubview(label)
    label.leftAnchor.constraint(equalTo: headerView.leftAnchor).isActive = true
    label.rightAnchor.constraint(equalTo: headerView.rightAnchor).isActive = true
    label.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
    label.heightAnchor.constraint(equalToConstant: 25).isActive = true

    return headerView

}

Ответ 7

Если вы используете titleForHeaderInSection, тогда самый простой способ - добавить в viewDidLoad():

self.tableView.backgroundColor = UIColor.clear

По какой-то причине установка ClearColor for Background в разделе View для TableView в построителе интерфейсов не всегда устанавливает прозрачность. Но добавление этой строки в код (по крайней мере для меня).

Ответ 8

Swift 4.

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView:UIView = UIView()
        headerView.backgroundColor = UIColor.lightGray
   return headerView
}

Ответ 9

Swift 5

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    guard let headerView = view as? UITableViewHeaderFooterView else { return }

    headerView.backgroundView?.backgroundColor = .red
}

И, если вы хотите разные цвета фона заголовка (и/или текста) для каждого раздела:

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    guard let headerView = view as? UITableViewHeaderFooterView else { return }

    switch section {

    case 0:
        headerView.backgroundView?.backgroundColor = .red
        headerView.textLabel?.textColor = .white
    case 1:
        headerView.backgroundView?.backgroundColor = .green
        headerView.textLabel?.textColor = .white
    case 2:
        headerView.backgroundView?.backgroundColor = .yellow
        headerView.textLabel?.textColor = .black

        // etc

    default:
        return
    }

Ответ 10

Это изменит его для всех заголовков в вашем приложении:

UITableViewHeaderFooterView.appearance().backgroundColor = theme.subViewBackgroundColor

Ответ 11

переопределить viewForHeaderInSection и создать UITableViewHeaderFooterView

 override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    var headrview = tableView.dequeueReusableHeaderFooterView(withIdentifier: "aaa")
    if headrview == nil {
        headrview = UITableViewHeaderFooterView(reuseIdentifier: "aaa")
    }
    let bview = UIView()
    bview.backgroundColor = Theme.current.navigationColor
    headrview?.backgroundView = bview
    headrview?.textLabel?.textColor = Theme.current.primaryTextColor
    return headrview
}

Ответ 12

Swift 4 меняет цвет фона и текста:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let tableView = view as? UITableViewHeaderFooterView else { return }
    tableView.backgroundView?.backgroundColor = UIColor.black
    tableView.textLabel?.textColor = UIColor.white
}