UITableViewHeaderFooterView проблема ширины на iOS 9 - PullRequest
0 голосов
/ 07 марта 2019

Я создал собственный заголовок 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
}

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 enter image description here

Результат на iOS10 и позже enter image description here

1 Ответ

0 голосов
/ 08 марта 2019

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

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) Создайте файл View, выбрав File> New> File. Выберите View под пользовательским интерфейсом. Назовите файл. Например, имя FooterView.xib.

b) Создайте файл подкласса UIView, выбрав «Файл»> «Создать»> «Файл». Выберите Какао Touch Class под источником. Назовите файл после выбора подкласса UIView. Например, имя FooterView.swift.

в) Выберите файл 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).

enter image description here

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
    }
}

enter image description here enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...