Проблема с шириной UITableViewHeaderFooterView в iOS 9

#ios #swift #uitableview #uitableviewsectionheader

#iOS #swift #uitableview #uitableviewsectionheader

Вопрос:

Я создал пользовательский заголовок TableView, создав подкласс UITableViewHeaderFooterView, он отлично работает на iOS 10 и более поздних версиях, но на iOS 9 ширина не регулируется границами TableView. Шаги, которые я использовал:- New File > CocoaTouchClass > CustomHeader:UITableViewCell . Я изменил UITableViewCell класс на UITableViewHeaderFooterView вручную.

2) Зарегистрировал его в viewDidLoad.

 tableView.register(UINib(nibName: "CustomHeader", bundle: nil),forHeaderFooterViewReuseIdentifier: CustomHeader.reuseIdentifier)

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let customHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: CustomHeader.reuseIdentifier) as! CustomHeader 
return customHeader
}
  

Пользовательский заголовок

 class CustomHeader: UITableViewHeaderFooterView {
class var reuseIdentifier: String{return String(describing: self)}

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    self.contentView.backgroundColor = UIColor(red: 244/255, green: 244/255, blue: 245/255, alpha: 1)
}
  

ViewController

 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let customHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: CustomHeader.reuseIdentifier) as! CustomHeader 
return customHeader
}
  

Результат в iOS 9
введите описание изображения здесь

Результат в iOS 10 и более поздних версиях
введите описание изображения здесь

Комментарии:

1. Вы не устанавливаете прямоугольник заголовка.

2. Я уже пробовал это ` CustomHeader.frame = CGRect(x: 0, y: 0, width: TableView.frame.width, height: 50)`, но результат все тот же.

3. Я не знаю, где вы это устанавливаете.

4. Я устанавливал это в viewForHeaderInSection

5. Создайте вид нижнего колонтитула с помощью UIView (xib).

Ответ №1:

Подход 1: создание представления нижнего колонтитула с UIView помощью кода in

 func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerRect = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0)
    let footerView = UIView(frame: footerRect)
    footerView.backgroundColor = UIColor.green
    let label = UILabel(frame: CGRect(x: 0.0, y: 4.0, width: 200.0, height: 20.0))
    label.text = "Hello"
    footerView.addSubview(label)
    return footerView
}
  

Подход 2: создание представления нижнего колонтитула с подключенным к IBOutlet UIView объектом (.xib)

a) Создайте файл просмотра, выбрав Файл> Создать> Файл. Выберите Просмотр в пользовательском интерфейсе. Назовите файл. Например, назовите footerView.xib.

б) Создайте UIView файл подкласса, выбрав Файл> Создать> Файл. Выберите класс Cocoa Touch в разделе Source. Назовите файл после выбора подкласса UIView. Например, назовите footerView.swift.

c) Выберите View файл. И выберите File's Owner в средней панели. Затем установите UIView имя подкласса (footerView) в качестве класса. Откройте как View файл, так и сам UIView subclass файл. Выполните подключение IBOutlet последнего к Content View первому.

 import UIKit

class FooterView: UIView {
    @IBOutlet var contentView: UIView!
    @IBOutlet weak var myLabel: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("FooterView", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        myLabel.text = "My footer"
    }
}
  

d) Добавьте UIView объект в контроллер представления. (Смотрите Рисунок ниже.) Задайте имя класса (footerView).

введите описание изображения здесь

e) Подключите объект просмотра нижнего колонтитула к контроллеру просмотра.

f) Подготовьтесь к viewForFooterInSection методу делегирования табличного представления.

 import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // MARK: - Variables
    let list = ["George", "Nancy", "Jim"]

    // MARK: - IBOutlet
    @IBOutlet var footerView: FooterView!
    @IBOutlet weak var tableView: UITableView!

    // MARK: - IBAction

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()


    }

    // MARK: - TableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = list[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerRect = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0)
        footerView.frame = footerRect
        return footerView
    }
}
  

введите описание изображения здесь
введите описание изображения здесь