UPD решено - см. отредактированный вопрос ниже
Попытка добавить настраиваемое представление (точнее, кнопку) в настраиваемый подкласс 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)
, но оба подхода ничего не сделали, ячейка появляется, но она пуста.
УПД прикрепление кода запуска 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
}
}
РЕШЕНО
в дополнение к ответу Sh_Khan требовалось установить
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 65
на столе
Вы должны либо реализовать
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)
])
Sh_Khan, пробовал оба способа, но они почему-то не сработали, подозревая проблему в объявлении таблицы, прикреплении кода, буду очень признателен за любую помощь или подсказку
спасибо, с вашей помощью удалось решить настройками rowHeight = UITableViewAutomaticDimension
и исправить estimatedRowHeight = 65
На мой взгляд, с кодом вашего сотового класса ничего не так. Не могли бы вы добавить свой код просмотра таблицы?
Я видел, что вы дважды использовали view.translatesAutoresizingMaskIntoConstraints = false. попробуйте удалить его внутри setupViews()
Я попытался запустить ваш код (кроме переключателя класса), и он работает при удалении autordranslte внутри setupViews для меня. Надеюсь, это поможет!
Будет ли это
self.translatesAutoresizingMaskIntoConstraints = false
еще одной проблемой в коде? Я думаю, что это будет игнорировать ограничения по высоте.