UITableViewCell incorrect dynamic height calculation with SwiftUI view inside on iOS 15 - uitableview

I am trying to use SwiftUI view inside UITableViewCell that is working fine until iOS 15. On iOS 15 when I scroll table view and once initial visible cells go off screen and new cells being reused those are having extra height added.
Following is the source code.
import UIKit
import SwiftUI
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
tableView?.register(TableViewCell.self, forCellReuseIdentifier: "cell")
tableView?.rowHeight = UITableView.automaticDimension
tableView?.estimatedRowHeight = 100
tableView?.separatorColor = .white
tableView?.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell
return cell ?? UITableViewCell()
}
}
class TableViewCell: UITableViewCell {
var stackView: UIStackView = {
let stack = UIStackView(frame: .zero)
stack.axis = .vertical
return stack
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
func setupView() {
contentView.clipsToBounds = true
contentView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
let hosting = UIHostingController(rootView: TestView())
stackView.addArrangedSubview(hosting.view)
hosting.view.backgroundColor = .red
}
}
struct TestView: View {
var body: some View {
Rectangle()
.fill(Color.green)
.frame(height: 100)
}
}
Any help will be highly appreciated. Thanks

Related

UITableView CustomCell Reuse (ImageView in CustomCell)

I'm pretty new to iOS dev and I have an issue with UITableViewCell.
I guess it is related to dequeuing reusable cell.
I added an UIImageView to my custom table view cell and also added a tap gesture to make like/unlike function (image changes from an empty heart(unlike) to a filled heart(like) as tapped and reverse). The problem is when I scroll down, some of the cells are automatically tapped. I found out why this is happening, but still don't know how to fix it appropriately.
Below are my codes,
ViewController
import UIKit
struct CellData {
var title: String
var done: Bool
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var models = [CellData]()
private let tableView: UITableView = {
let table = UITableView()
table.register(TableViewCell.self, forCellReuseIdentifier: TableViewCell.identifier)
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
configure()
}
private func configure() {
self.models = Array(0...50).compactMap({
CellData(title: "\($0)", done: false)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as? TableViewCell else {
return UITableViewCell()
}
cell.textLabel?.text = model.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadData()
}
}
TableViewCell
import UIKit
class TableViewCell: UITableViewCell {
let mainVC = ViewController()
static let identifier = "TableViewCell"
let likeImage: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "heart")
imageView.tintColor = .darkGray
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(likeImage)
layout()
//Tap Gesture Recognizer 실행하기
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapImageView(_:)))
likeImage.addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
}
private func layout() {
likeImage.widthAnchor.constraint(equalToConstant: 30).isActive = true
likeImage.heightAnchor.constraint(equalToConstant: 30).isActive = true
likeImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
likeImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
}
#objc func didTapImageView(_ sender: UITapGestureRecognizer) {
if likeImage.image == UIImage(systemName: "heart.fill"){
likeImage.image = UIImage(systemName: "heart")
likeImage.tintColor = .darkGray
} else {
likeImage.image = UIImage(systemName: "heart.fill")
likeImage.tintColor = .systemRed
}
}
}
This gif shows how it works now.
enter image description here
I've tried to use "done" property in CellData structure to capture the status of the uiimageview but failed (didn't know how to use that in the correct way).
I would be so happy if anyone can help this!
You've already figured out that the problem is cell reuse.
When you dequeue a cell to be shown, you are already setting the cell label's text based on your data:
cell.textLabel?.text = model.title
you also need to tell the cell whether to show the empty or filled heart image.
And, when the user taps that image, your cell needs to tell the controller to update the .done property of your data model.
That can be done with either a protocol/delegate pattern or, more commonly (particularly with Swift), using a closure.
Here's a quick modification of the code you posted... the comments should give you a good idea of what's going on:
struct CellData {
var title: String
var done: Bool
}
class ShinViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var models = [CellData]()
private let tableView: UITableView = {
let table = UITableView()
table.register(ShinTableViewCell.self, forCellReuseIdentifier: ShinTableViewCell.identifier)
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
configure()
}
private func configure() {
self.models = Array(0...50).compactMap({
CellData(title: "\($0)", done: false)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ShinTableViewCell.identifier, for: indexPath) as! ShinTableViewCell
let model = models[indexPath.row]
cell.myLabel.text = model.title
// set the "heart" to true/false
cell.isLiked = model.done
// closure
cell.callback = { [weak self] theCell, isLiked in
guard let self = self,
let pth = self.tableView.indexPath(for: theCell)
else { return }
// update our data
self.models[pth.row].done = isLiked
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
class ShinTableViewCell: UITableViewCell {
// we'll use this closure to communicate with the controller
var callback: ((UITableViewCell, Bool) -> ())?
static let identifier = "TableViewCell"
let likeImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "heart")
imageView.tintColor = .darkGray
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let myLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
// we'll load the heart images once in init
// instead of loading them every time they change
var likeIMG: UIImage!
var unlikeIMG: UIImage!
var isLiked: Bool = false {
didSet {
// update the image in the image view
likeImageView.image = isLiked ? likeIMG : unlikeIMG
// update the tint
likeImageView.tintColor = isLiked ? .systemRed : .darkGray
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// make sure we load the heart images
guard let img1 = UIImage(systemName: "heart"),
let img2 = UIImage(systemName: "heart.fill")
else {
fatalError("Could not load the heart images!!!")
}
unlikeIMG = img1
likeIMG = img2
// add label and image view
contentView.addSubview(myLabel)
contentView.addSubview(likeImageView)
layout()
//Tap Gesture Recognizer 실행하기
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapImageView(_:)))
likeImageView.addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
}
private func layout() {
// let's use the "built-in" margins guide
let g = contentView.layoutMarginsGuide
// image view bottom constraint
let bottomConstraint = likeImageView.bottomAnchor.constraint(equalTo: g.bottomAnchor)
// this will avoid auto-layout complaints
bottomConstraint.priority = .required - 1
NSLayoutConstraint.activate([
// constrain label leading
myLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
// center the label vertically
myLabel.centerYAnchor.constraint(equalTo: g.centerYAnchor),
// constrain image view trailing
likeImageView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// constrain image view to 30 x 30
likeImageView.widthAnchor.constraint(equalToConstant: 30),
likeImageView.heightAnchor.constraint(equalTo: likeImageView.widthAnchor),
// constrain image view top
likeImageView.topAnchor.constraint(equalTo: g.topAnchor),
// activate image view bottom constraint
bottomConstraint,
])
}
#objc func didTapImageView(_ sender: UITapGestureRecognizer) {
// toggle isLiked (true/false)
isLiked.toggle()
// inform the controller, so it can update the data
callback?(self, isLiked)
}
}

SwiftUI view does not resize despite automaticDimension in UIKit TableViewCell

I am reusing a SwiftUI view in a UIKit TableViewCell but the cell is not resizing accordingly despite having automaticDimension set.
Code:
class TestController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Test"
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
tableView.register(TestCell.self, forCellReuseIdentifier: "cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TestCell
cell.title = "Title \(indexPath.row)"
return cell
}
}
class TestCell: UITableViewCell {
var host: UIHostingController<TestView>?
var title: String? {
didSet {
if let title = title {
if host == nil {
let hostingController = UIHostingController(rootView: TestView(text: title))
host = hostingController
let hostingView = hostingController.view
hostingView?.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(hostingView ?? UIView())
hostingView?.topAnchor.constraint(equalTo: topAnchor, constant: 40).isActive = true
hostingView?.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
hostingView?.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
hostingView?.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -40).isActive = true
} else {
host?.rootView = TestView(text: title)
}
setNeedsLayout()
}
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct TestView: View {
var text: String
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(text)
.font(.headline)
Text("Subtitle")
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
}
.padding()
}
}
Results:
Notice the exaggerated constant of 40 inside the didSet method, the code seems to push the content downwards correctly, but it does not expand the height of the cell.

Tableview cells disappear upon scrolling down an up except for the last cell from each section which turns grey color

I am creating a tableview programmatically which is not a problem,
but making a programmatic table view cell is being a headache, it is the first time I do this.
I don't know what I am doing wrong as much as I have tried, I cannot debug this.
Here is the code for the view controller
import Foundation
import UIKit
extension CountryPhoneCodeList {
class ViewController : UIViewController {
var viewModel: ViewModel!
var router: Router!
private lazy var tableView: UITableView = {
let table = UITableView(frame: .zero, style: .grouped)
table.translatesAutoresizingMaskIntoConstraints = false
table.dataSource = self
table.delegate = self
table.register(CountryPhoneCodeListCell.self, forCellReuseIdentifier: "CountryPhoneCodeListCell")
table.layer.backgroundColor = UIColor.white.cgColor
table.estimatedRowHeight = 44
table.rowHeight = UITableView.automaticDimension
table.separatorStyle = .none
return table
}()
var updateTextFieldCode : ((String, String) -> ())? = nil
override func viewDidLoad() {
self.configureUI()
}
private func configureUI(){
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
}
extension CountryPhoneCodeList.ViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedViewModel = viewModel.cellViewModelAt(section: indexPath.section, row: indexPath.row)
updateTextFieldCode?(selectedViewModel.flag, selectedViewModel.countryPhoneCode)
router.dismiss()
}
}
extension CountryPhoneCodeList.ViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.countryCodeListCellViewModels.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let character = viewModel.getAlphabetCharacterFromIndex(index: section)
guard let countryCodesStartingWithCharacter = viewModel.countryCodeListCellViewModels[character] else {fatalError("Could not get codes starting with letter \(character)")}
return countryCodesStartingWithCharacter.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect.zero)
let label = UILabel(frame: CGRect(x: 14, y: -8, width: 50, height: 50))
label.text = viewModel.getAlphabetCharacterFromIndex(index: section)
label.customise(for: .bodyBold)
view.addSubview(label)
view.backgroundColor = .white
return view
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "CountryPhoneCodeListCell", for: indexPath) as? CountryPhoneCodeListCell {
cell.viewModel = viewModel.cellViewModelAt(section: indexPath.section, row: indexPath.row)
cell.selectionStyle = .none
return cell
}
return UITableViewCell()
}
}
class CountryPhoneCodeListViewController : CountryPhoneCodeList.ViewController {}
And this is the code for the tableview cell
import UIKit
struct CountryPhoneCodeListCellViewModel {
var countryName = ""
var countryPhoneCode = ""
var flag = ""
}
class CountryPhoneCodeListCell: UITableViewCell {
private var countryNameLabel: UILabel = .buildBodyLabel()
private var countryPhoneCodeLabel: UILabel = .buildBodyLabel()
var viewModel: CountryPhoneCodeListCellViewModel? {
didSet {
guard let viewModel = viewModel else {fatalError("Cannot unwrap viewModel")}
countryNameLabel.text = viewModel.countryName
countryNameLabel.customise(for: .body)
countryPhoneCodeLabel.text = viewModel.countryPhoneCode
countryPhoneCodeLabel.customise(for: .body)
}
}
override func prepareForReuse() {
countryNameLabel.text = nil
countryPhoneCodeLabel.text = nil
}
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(countryNameLabel)
contentView.addSubview(countryPhoneCodeLabel)
NSLayoutConstraint.activate([
countryNameLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: .constant16),
countryNameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: .constant16),
countryNameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: .constant4),
countryPhoneCodeLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: .constant16),
countryPhoneCodeLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: .constant16),
countryPhoneCodeLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: .constant16)
])
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}

How to create custom cells 100% programmatically in Swift?

I am trying to build a TableView programmatically, but I cannot get a basic standard label to display; all I see is basic empty cells. Here's my code:
TableView Cell:
class TableCell: UITableViewCell {
let cellView: UIView = {
let view = UIView()
view.backgroundColor = .systemRed
return view
}()
let labelView: UILabel = {
let label = UILabel()
label.text = "Cell 1"
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
addSubview(cellView)
NSLayoutConstraint.activate([
cellView.topAnchor.constraint(equalTo: topAnchor),
cellView.bottomAnchor.constraint(equalTo: bottomAnchor),
cellView.leadingAnchor.constraint(equalTo: leadingAnchor),
cellView.trailingAnchor.constraint(equalTo: trailingAnchor)])
cellView.addSubview(labelView)
}
}
Data Source:
class TableDataSource: NSObject, UITableViewDataSource {
let cellID = "cell"
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! TableCell
return cell
}
}
And this is the VC:
class TableViewController: UITableViewController {
let dataSource = TableDataSource()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TableCell.self, forCellReuseIdentifier: dataSource.cellID)
tableView.dataSource = dataSource
}
}
I am trying to keep the code as basic as possible for future references. I've set various breakpoints to see what could go wrong, but they all check out. Could it be the constraints that are wrong?
Any help is appreciated.
I see several errors in your cell.
Add subviews to contentView, not directly to cell:
contentView.addSubview(cellView)
cellView.addSubview(labelView)
The same is necessary for constraints:
NSLayoutConstraint.activate([
cellView.topAnchor.constraint(equalTo: contentView.topAnchor),
cellView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
cellView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
cellView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
])
Views created in code need to set translatesAutoresizingMaskIntoConstraints = false,
let cellView: UIView = {
let view = UIView()
view.backgroundColor = .systemRed
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let labelView: UILabel = {
let label = UILabel()
label.text = "Cell 1"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
There are no constraints for your label.
Your constraints don't work, because you need to change translatesAutoresizingMaskIntoConstraints for cellView in your setup():
func setup() {
addSubview(cellView)
cellView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
cellView.topAnchor.constraint(equalTo: topAnchor),
cellView.bottomAnchor.constraint(equalTo: bottomAnchor),
cellView.leadingAnchor.constraint(equalTo: leadingAnchor),
cellView.trailingAnchor.constraint(equalTo: trailingAnchor)])
cellView.addSubview(labelView)
}

how to add custom view on UITableViewCell programatically?

UPD Resolved - see edited question below
Trying to add a custom view (button, to be more specific) to a custom subclass of UITableViewCell but unable to see any layout results on iOS 10.1 on the device. Did not see any changes on the layout, and tried to just fill the cell with a custom view with the red background but failed to achieve this result as well.
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
}
}
What I tried besides that: using plain addSubiew and constraint to the self anchors of the cell, and add to contentView in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) but both approaches did nothing, the cell appears but it is empty.
UPD
attaching the TableView initiation code for the reference
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
in addition to Sh_Khan answer, it was required to set
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 65
on the table
It doesn't look like it's anything wrong with the code in your cell class in my eyes. Can you please add your tableviewcode?
You should either implement
heightForRowAt
Or add
containerView.heightAnchor.constraint(equalToConstant:200).isActive = true
Also add any subview to 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)
])

Resources