Как добавить пользовательский вид на UITableViewCell программно? - PullRequest
0 голосов
/ 07 апреля 2019

UPD Resolved - см. Отредактированный вопрос ниже

Попытка добавить настраиваемое представление (кнопка, если быть более точным) в настраиваемый подкласс UITableViewCell, но не удается увидеть результаты макета наiOS 10.1 на устройстве.Не увидел никаких изменений в макете, и попытался просто заполнить ячейку с настраиваемым видом на красном фоне, но также не смог достичь этого результата.

import UIKit

class Save: UITableViewCell {

    let containerView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .red
        return view
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    func setupViews() {
        self.translatesAutoresizingMaskIntoConstraints = false
        addSubview(containerView)
        containerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        containerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        containerView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

    }

}

Кроме того, что я пробовал: с помощью простого addSubiew и ограничения на якоря self и добавление в contentView в tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath), но оба подхода ничего не сделали, ячейка появляется, но она естьпусто.

UPD с кодом инициализации TableView для ссылки

class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let settings = [
        "setting1",
        "setting2",
        "setting3",
        "setting4",
        "setting5",
        "setting6",
        "setting7"
    ]


    let overlay: UIView = {
        var view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .gray
        view.alpha = 0.3
        view.isHidden = true
        return view
    }()



    let tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "commonCell")
        tableView.register(Save.self, forCellReuseIdentifier: "btnCell")
        tableView.register(Switcher.self, forCellReuseIdentifier: "switcherCell")
        tableView.headerView(forSection: 0)?.textLabel?.text = "settings of app"
        tableView.tableFooterView = UIView()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = UITableViewAutomaticDimension
        tableView.allowsSelection = false
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }

    func setupViews() {
        view.backgroundColor = .white
        view.addSubview(tableView)

        tableView.dataSource = self
        tableView.delegate = self

        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true


    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        tabBarController?.navigationItem.rightBarButtonItems = []
        tabBarController?.navigationItem.title = "settings"
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return settings.count
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "commonCell", for: indexPath)
        cell.textLabel?.text = settings[indexPath.row]
        if(indexPath.row == 6) {
            cell.textLabel?.text = ""
            cell = tableView.dequeueReusableCell(withIdentifier: "btnCell", for: indexPath)
        }
        return cell
    }


}

RESOLVED

в дополнение к ответу Sh_KhanТребовалось установить

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 65

на стол

Ответы [ 2 ]

1 голос
/ 07 апреля 2019

Не похоже, что с кодом в вашем классе ячеек все в порядке.Можете ли вы добавить свой код tableview?

0 голосов
/ 07 апреля 2019

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

heightForRowAt

Или добавить

containerView.heightAnchor.constraint(equalToConstant:200).isActive = true

Также добавьте любое подпредставление к contentView

contentView.addSubview(containerView)
NSLayoutConstraint.activate([ 
    containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
    containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
    containerView.topAnchor.constraint(equalTo: contentView.topAnchor),
    containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
    containerView.heightAnchor.constraint(equalToConstant:200)
])  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...