Отступ для заголовка в таблице - PullRequest
0 голосов
/ 04 февраля 2020

У меня есть таблица с двумя разделами. Свойство textAligment = .right для заголовочных разделов. Но это слишком близко к границе телефона. Как сделать отступ от границы ближе к центру?

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

        let header = view as! UITableViewHeaderFooterView

        header.textLabel?.textColor = .black
        header.textLabel?.textAlignment = .right

    }

1 Ответ

1 голос
/ 04 февраля 2020

Вот очень простой пример ...

  • Добавление UITableViewController в раскадровку.
  • Назначьте свой пользовательский класс SectionTableViewController (из кода ниже).
  • Используйте ячейку по умолчанию.
  • Присвойте ячейке идентификатор "DefCell"

Запустите приложение. Вот что вы должны увидеть:

enter image description here

Я ограничил использование метки contentView.layoutMarginsGuide и установил конечную константу -32

class MySectionHeaderView: UITableViewHeaderFooterView {

    let myLabel: UILabel = {
        let v = UILabel()

        v.translatesAutoresizingMaskIntoConstraints = false
        v.textColor = .black
        v.textAlignment = .right

        // during development, give it a background color to make it easy to see the frame
        //v.backgroundColor = .cyan

        return v
    }()

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        commonInit()
    }

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

    func commonInit() -> Void {

        contentView.addSubview(myLabel)

        // use layout margins guide
        let g = contentView.layoutMarginsGuide

        NSLayoutConstraint.activate([
            myLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            myLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
            myLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),

            // set the constant to provide more trailing space as desired
            // Note: must be a negative value
            myLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -32.0),
        ])

    }

}

class SectionTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(MySectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "MyHeader")
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 10
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let c = tableView.dequeueReusableCell(withIdentifier: "DefCell", for: indexPath)
        c.textLabel?.text = "Section: \(indexPath.section) Row: \(indexPath.row)"
        return c
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard let v = tableView.dequeueReusableHeaderFooterView(withIdentifier: "MyHeader") as? MySectionHeaderView else {
            fatalError("Could not dequeue MySectionHeaderView!")
        }
        v.myLabel.text = "Section \(section)"
        return v
    }

}

Вы заметите эти строки в объявлении myLabel в MySectionHeaderView:

    // during development, give it a background color to make it easy to see the frame
    //v.backgroundColor = .cyan

Так выглядит, когда метка имеет цвет фона, так что вы можете легко увидеть, как размещена этикетка:

enter image description here

...