Swift 4: Two UITableView in one UIViewController, scroll function not working - ios

I have two UITableView in one UIViewController and feeding those tables with data from Rest API. it all seems works fine but then I realize that the scrolling is not working. I have other UITableViewController with scrolling working just fine.
here is the code of my ViewController
here is the class
class DashboardController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var lowerTableView: UITableView = {
let tv = UITableView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.isScrollEnabled = true
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell1")
return tv
}()
var upperTableView: UITableView = {
let tv = UITableView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.isScrollEnabled = true
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tv
}()
...
viewDidLoad() function
override func viewDidLoad() {
super.viewDidLoad()
if user?.status != "success" {
handleLogout()
} else {
self.navigationItem.title = "Dashboard"
self.userName.text = user?.fullname
upperTableView.dataSource = self
upperTableView.delegate = self
lowerTableView.dataSource = self
lowerTableView.delegate = self
handleRefresh()
upperTableView.register(QuizCell.self, forCellReuseIdentifier: "cell")
lowerTableView.register(QuizCell.self, forCellReuseIdentifier: "cell1")
setupNavBarButtons()
setupDashboard()
}
}
...
and numberOfRowsInSection method
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int?
if tableView == self.upperTableView {
count = sampleData.count
// count = 10
}
if tableView == self.lowerTableView {
count = closedQuizList.count
// count = 10
}
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.upperTableView {
cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let datum = sampleData[indexPath.row]
cell?.textLabel?.text = datum.name
cell?.detailTextLabel?.text = datum.quiz_type+" - "+datum.start_date!+" - "+datum.end_date!
cell?.detailTextLabel?.textColor = .blue
}
if tableView == self.lowerTableView {
cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
let datum = closedQuizList[indexPath.row]
cell?.textLabel?.text = datum.name + " (" + datum.score! + ")"
}
return cell!
}
here is setupDashboard() code
func setupDashboard() {
let upperDashboard = UIView()
upperDashboard.backgroundColor = .white
let lowerDashboard = UIView()
lowerDashboard.backgroundColor = .white
let dashboardStackView = UIStackView(arrangedSubviews: [upperDashboard, lowerDashboard])
dashboardStackView.translatesAutoresizingMaskIntoConstraints = false
dashboardStackView.distribution = .fillEqually
dashboardStackView.axis = .vertical
view.addSubview(dashboardStackView)
NSLayoutConstraint.activate([
dashboardStackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
dashboardStackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
dashboardStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
dashboardStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
// upperDashboard part
upperDashboard.addSubview(userName)
upperDashboard.addSubview(userStatus)
upperDashboard.addSubview(upperLabel)
upperDashboard.addSubview(upperLabelSeparator)
upperDashboard.addSubview(statsButton)
upperDashboard.addSubview(upperTableView)
NSLayoutConstraint.activate([
// userName
userName.topAnchor.constraint(equalTo: upperDashboard.topAnchor, constant: 10),
userName.leftAnchor.constraint(equalTo: upperDashboard.leftAnchor, constant: 12),
userName.widthAnchor.constraint(equalTo: upperDashboard.widthAnchor, multiplier: 0.5),
// userStatus
userStatus.topAnchor.constraint(equalTo: upperDashboard.topAnchor, constant: 10),
userStatus.rightAnchor.constraint(equalTo: upperDashboard.rightAnchor, constant: -12),
userStatus.widthAnchor.constraint(equalTo: upperDashboard.widthAnchor, multiplier: 0.5),
// upperLabel
statsButton.topAnchor.constraint(equalTo: userName.bottomAnchor, constant: 6),
statsButton.leftAnchor.constraint(equalTo: upperDashboard.leftAnchor, constant: 12),
statsButton.widthAnchor.constraint(equalTo: upperDashboard.widthAnchor, constant: -24),
statsButton.heightAnchor.constraint(equalToConstant: 40),
// statsButton
upperLabel.topAnchor.constraint(equalTo: statsButton.bottomAnchor, constant: 6),
upperLabel.leadingAnchor.constraint(equalTo: statsButton.leadingAnchor),
upperLabel.widthAnchor.constraint(equalTo: statsButton.widthAnchor),
// upperLabelSeparator
upperLabelSeparator.topAnchor.constraint(equalTo: upperLabel.bottomAnchor),
upperLabelSeparator.leadingAnchor.constraint(equalTo: upperLabel.leadingAnchor),
upperLabelSeparator.widthAnchor.constraint(equalTo: upperLabel.widthAnchor),
upperLabelSeparator.heightAnchor.constraint(equalToConstant: 4),
// upperTableView
upperTableView.topAnchor.constraint(equalTo: upperLabelSeparator.bottomAnchor),
upperTableView.trailingAnchor.constraint(equalTo: lowerDashboard.trailingAnchor, constant: -12),
upperTableView.leadingAnchor.constraint(equalTo: lowerDashboard.leadingAnchor, constant: 12),
upperTableView.bottomAnchor.constraint(equalTo: lowerDashboard.bottomAnchor)
])
// lowerDashboard part
lowerDashboard.addSubview(lowerLabel)
lowerDashboard.addSubview(lowerLabelSeparator)
lowerDashboard.addSubview(lowerTableView)
NSLayoutConstraint.activate([
// lowerLabel
lowerLabel.topAnchor.constraint(equalTo: lowerDashboard.topAnchor),
lowerLabel.leftAnchor.constraint(equalTo: lowerDashboard.leftAnchor, constant: 12),
lowerLabel.widthAnchor.constraint(equalTo: lowerDashboard.widthAnchor, constant: -24),
// lowerLabelSeparator
lowerLabelSeparator.topAnchor.constraint(equalTo: lowerLabel.bottomAnchor),
lowerLabelSeparator.leadingAnchor.constraint(equalTo: lowerLabel.leadingAnchor),
lowerLabelSeparator.widthAnchor.constraint(equalTo: lowerLabel.widthAnchor),
lowerLabelSeparator.heightAnchor.constraint(equalToConstant: 4),
// lowerTableView
lowerTableView.topAnchor.constraint(equalTo: lowerLabelSeparator.bottomAnchor),
lowerTableView.trailingAnchor.constraint(equalTo: lowerDashboard.trailingAnchor, constant: -12),
lowerTableView.leadingAnchor.constraint(equalTo: lowerDashboard.leadingAnchor, constant: 12),
lowerTableView.bottomAnchor.constraint(equalTo: lowerDashboard.bottomAnchor)
])
}

class DashboardController: UIViewController, UITableViewDataSource, UITableViewDelegate {
lazy var lowerTableView: UITableView = {
let tv = UITableView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.isScrollEnabled = true
tv.isUserInteractionEnabled = true
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell1")
return tv
}()
lazy var upperTableView: UITableView = {
let tv = UITableView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.isScrollEnabled = true
tv.isUserInteractionEnabled = true
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tv
}()
This way you don't have to set the delegate and dataSource inside of viewDidLoad.
I also would not call tableview.register again inside viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
if user?.status != "success" {
handleLogout()
} else {
self.navigationItem.title = "Dashboard"
self.userName.text = user?.fullname
self.view.addSubView(lowerTableView)
self.view.addSUbView(upperTableView)
handleRefresh()
setupNavBarButtons()
setupDashboard()
}
}
If this doesn't work can you show me what setupDashboard() does?

Related

trouble with constructs after adding view to contentView

I need to add a target to an image in a tableview, but it doesn't work if I don't add a view to the contentView. After that, my constraints broke.
https://github.com/termyter/stackoverflow-search
beforeenter image description here
afterenter image description here
PostController
import Foundation
import UIKit
protocol AnswerhNetworkDelegate: AnyObject {
func getListModels(noteModels: [AnswerModel])
}
class PostController: UIViewController, UITableViewDelegate, UITableViewDataSource, AnswerhNetworkDelegate{
func getListModels(noteModels: [AnswerModel]) {
listModels += noteModels
table.reloadData()
}
private var listModels: [AnswerModel] = []
private var searchText = UITextField()
private var searchButton = UIButton()
private var table = UITableView()
private let answerNetwork = AnswerNetwork()
var model: PostModel = PostModel.empty
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
table.register(PostCell.self, forCellReuseIdentifier: "PostCell")
table.register(CustomAnswerCell.self, forCellReuseIdentifier: "CustomAnswerCell")
table.delegate = self
table.dataSource = self
table.estimatedRowHeight = 68.0
table.rowHeight = UITableView.automaticDimension
setupUI()
answerNetwork.answerNetworkDelegate = self
//переделать
answerNetwork.fetch(idPost: model.id)
}
override func viewDidAppear(_ animated: Bool) {
table.reloadData()
}
private func setupUI() {
table.translatesAutoresizingMaskIntoConstraints = false
table.separatorStyle = .none
view.addSubview(table)
table.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
table.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
table.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
table.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
listModels.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as? PostCell else {
fatalError("не CustomCell")
}
// cell.cellView.image.userInteractionEnabled =
let lpgr = UITapGestureRecognizer(target: self, action: #selector(PostController.handleTapPress(_:)))
cell.cellView.image.isUserInteractionEnabled = true
cell.cellView.image.addGestureRecognizer(lpgr)
cell.selectionStyle = .none
cell.model = model
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomAnswerCell", for: indexPath) as? CustomAnswerCell else {
fatalError("не CustomCell")
}
cell.selectionStyle = .none
cell.model = listModels[indexPath.row - 1]
return cell
}
}
#objc func handleTapPress(_ sender: Any){
UIApplication.shared.openURL(URL(string: model.link)!)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
extension String {
init?(htmlEncodedString: String) {
guard let data = htmlEncodedString.data(using: .utf8) else {
return nil
}
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
return nil
}
self.init(attributedString.string)
}
}
PostCell
import Foundation
import UIKit
class PostCell: UITableViewCell {
var cellView = PostView()
private var selectedButton = UIButton(type: .custom)
var model: PostModel? {
get {
cellView.model
}
set {
cellView.model = newValue ?? PostModel.empty
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .white
setupView()
// print(cellView.frame)
// print(contentView.frame)
// print(self.frame)
}
override func prepareForReuse() {
super.prepareForReuse()
isHidden = false
isSelected = false
isHighlighted = false
self.model = PostModel.empty
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
cellView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(cellView)
// addSubview(cellView)
cellView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor).isActive = true
cellView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor).isActive = true
cellView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
cellView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -5).isActive = true
}
}
PostView is in the PostCell as a cell and is injected with the Model
import Foundation
import UIKit
class PostView: UIView {
private var titleText = UILabel()
private var bodyText = UILabel()
private var nameText = UILabel()
var image = UIImageView()
private var dateText = UILabel()
private var answerCount = UILabel()
var model: PostModel = PostModel.empty {
didSet {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.YYY"
titleText.text = model.title
image.load(urlString: model.image)
nameText.text = "Автор:" + model.name
dateText.text = "Дата: " + formatter.string(from: model.date)
answerCount.text = "Кол-во ответов: " + String(model.answer_count)
bodyText.text = model.body
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .systemBackground
setupTitleText()
setupImage()
let tapGR = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped))
image.addGestureRecognizer(tapGR)
image.isUserInteractionEnabled = true
setupNameText()
setupDateText()
setupAnswerCount()
setupBodyText()
}
#objc func imageTapped(sender: UITapGestureRecognizer) {
if sender.state == .ended {
UIApplication.shared.openURL(URL(string: model.link)!)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTitleText() {
titleText.translatesAutoresizingMaskIntoConstraints = false
titleText.numberOfLines = 0
let maximumLabelSize: CGSize = CGSize(width: 280, height: 9999)
let expectedLabelSize: CGSize = titleText.sizeThatFits(maximumLabelSize)
var newFrame: CGRect = titleText.frame
newFrame.size.height = expectedLabelSize.height
titleText.frame = newFrame
addSubview(titleText)
titleText.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
titleText.leadingAnchor.constraint( equalTo: leadingAnchor, constant: 10).isActive = true
titleText.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
}
private func setupImage() {
image.translatesAutoresizingMaskIntoConstraints = false
image.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
addSubview(image)
image.topAnchor.constraint(equalTo: titleText.bottomAnchor, constant: 5).isActive = true
image.leadingAnchor.constraint( equalTo: leadingAnchor, constant: 10).isActive = true
image.trailingAnchor.constraint(equalTo: leadingAnchor, constant: 60).isActive = true
//image.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true
}
private func setupNameText() {
nameText.translatesAutoresizingMaskIntoConstraints = false
addSubview(nameText)
nameText.topAnchor.constraint(equalTo: titleText.bottomAnchor, constant: 5).isActive = true
nameText.leadingAnchor.constraint( equalTo: image.trailingAnchor, constant: 10).isActive = true
nameText.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
}
private func setupDateText() {
dateText.translatesAutoresizingMaskIntoConstraints = false
addSubview(dateText)
dateText.topAnchor.constraint(equalTo: nameText.bottomAnchor, constant: 5).isActive = true
dateText.leadingAnchor.constraint( equalTo: image.trailingAnchor, constant: 10).isActive = true
dateText.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
}
private func setupAnswerCount() {
answerCount.translatesAutoresizingMaskIntoConstraints = false
addSubview(answerCount)
answerCount.topAnchor.constraint(equalTo: dateText.bottomAnchor, constant: 5).isActive = true
answerCount.leadingAnchor.constraint( equalTo: image.trailingAnchor, constant: 10).isActive = true
answerCount.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
// answerCount.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true
}
private func setupBodyText() {
bodyText.translatesAutoresizingMaskIntoConstraints = false
bodyText.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
bodyText.translatesAutoresizingMaskIntoConstraints = false
bodyText.numberOfLines = 0
let maximumLabelSize: CGSize = CGSize(width: 280, height: 9999)
let expectedLabelSize: CGSize = bodyText.sizeThatFits(maximumLabelSize)
// create a frame that is filled with the UILabel frame data
var newFrame: CGRect = bodyText.frame
// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height
// put calculated frame into UILabel frame
bodyText.frame = newFrame
addSubview(bodyText)
bodyText.topAnchor.constraint(equalTo: answerCount.bottomAnchor, constant: 5).isActive = true
bodyText.leadingAnchor.constraint( equalTo: leadingAnchor, constant: 5).isActive = true
bodyText.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5).isActive = true
bodyText.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true
}
}
on this github, I looked at how he arranges the constraints and made it for himself https://github.com/jeantimex/ios-swift-collapsible-table-section/blob/master/ios-swift-collapsible-table-section/CollapsibleTableViewCell.swift
and redid PostCell
private func setupView() {
let marginGuide = contentView.layoutMarginsGuide
cellView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(cellView)
cellView.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true
cellView.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true
cellView.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor, constant: -5).isActive = true
cellView.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true
}

Struggling to adjust cell height with increase in content

I have been struggling greatly almost regularly to be able to create a cell whose height adjusts with content while trying to do it programatically, some things i am trying are , image shows the problem
use below function
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
2)Use this in viewDidLoad
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
Setting bottom and top constraints to equal rather then not equal
Below i paste some code to show my struggle or trying every thing to get the cell to expand with content, which it does. not, can any one please suggest some ways to achieve it
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = restaurantMainTable.dequeueReusableCell(withIdentifier: String(describing: RestaurantMainViewCells.self), for: indexPath) as! RestaurantMainViewCells
cell.heightAnchor.constraint(greaterThanOrEqualToConstant: 60).isActive = true
view.addSubview(cell)
view.addSubview(cell.contentView)
view.addSubview(cell.restaurantName)
view.addSubview(cell.restaurantType)
view.addSubview(cell.restaurantLocation)
view.addSubview(cell.restaurantMiniImage)
view.addSubview(cell.restaurantHeartImage)
cell.restaurantHeartImage.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantMiniImage.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantName.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantLocation.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantType.translatesAutoresizingMaskIntoConstraints = false
//Fonts
let font = UIFont(name: "Rubik-Medium", size: 18)
let fontMetrics = UIFontMetrics(forTextStyle: .body)
let labels = [cell.restaurantName, cell.restaurantLocation, cell.restaurantType]
labels.forEach { label in
label.font = fontMetrics.scaledFont(for: font!)
}
let stackLabels = UIStackView()
view.addSubview(stackLabels)
stackLabels.alignment = .top
stackLabels.distribution = .fill
stackLabels.spacing = 5
stackLabels.axis = .vertical
stackLabels.addArrangedSubview(cell.restaurantName)
stackLabels.addArrangedSubview(cell.restaurantType)
stackLabels.addArrangedSubview(cell.restaurantLocation)
let stackImage = UIStackView()
view.addSubview(stackImage)
stackLabels.translatesAutoresizingMaskIntoConstraints = false
stackImage.alignment = .top
stackImage.distribution = .fill
stackImage.axis = .horizontal
stackImage.spacing = 5
cell.restaurantMiniImage.heightAnchor.constraint(equalToConstant: 60).isActive = true
cell.restaurantMiniImage.widthAnchor.constraint(equalToConstant: 60).isActive = true
cell.restaurantMiniImage.layer.cornerRadius = 30
cell.restaurantMiniImage.clipsToBounds = true
cell.restaurantHeartImage.heightAnchor.constraint(equalToConstant: 20).isActive = true
cell.restaurantHeartImage.widthAnchor.constraint(equalToConstant: 20).isActive = true
cell.restaurantHeartImage.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -10).isActive = true
cell.restaurantHeartImage.topAnchor.constraint(equalTo: cell.topAnchor, constant: 20).isActive = true
stackImage.addArrangedSubview(cell.restaurantMiniImage)
stackImage.addArrangedSubview(stackLabels)
view.addSubview(stackImage)
stackImage.translatesAutoresizingMaskIntoConstraints = false
stackImage.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 10).isActive = true
stackImage.topAnchor.constraint(greaterThanOrEqualTo: cell.topAnchor, constant: 10).isActive = true
// stackImage.topAnchor.constraint(equalTo: cell.topAnchor, constant: 10).isActive = true
stackImage.trailingAnchor.constraint(equalTo: cell.restaurantHeartImage.leadingAnchor, constant: -10).isActive = true
// stackImage.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: -10).isActive = true
stackImage.bottomAnchor.constraint(greaterThanOrEqualTo: cell.bottomAnchor, constant: -10).isActive = true
cell.restaurantName.text = restaurants[indexPath.row].name
cell.restaurantType.text = restaurants[indexPath.row].type
cell.restaurantLocation.text = restaurants[indexPath.row].location
cell.restaurantHeartImage.image = UIImage(named: "heart-tick")
if let restaurantImage = restaurants[indexPath.row].image {
cell.restaurantMiniImage.image = UIImage(data: restaurantImage as Data)
}
return cell
default:
fatalError("no data found")
}
}
UPDATE - The whole class
//
// RestaurantMainController.swift
// LaVivaRepeat
//
//
import UIKit
import CoreData
class RestaurantMainController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {
var restaurants: [Restaurant] = []
var fetchResultController: NSFetchedResultsController<Restaurant>!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurants.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
let restaurantMainTable = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(restaurantMainTable)
//MARK:- add delegates as self, always, else no contact with model will take place
restaurantMainTable.rowHeight = UITableView.automaticDimension
restaurantMainTable.estimatedRowHeight = 60
self.restaurantMainTable.delegate = self
self.restaurantMainTable.dataSource = self
self.restaurantMainTable.separatorStyle = .singleLine
//MARK:- create a view to show when no records are there
let backGroundView = UIView()
view.addSubview(backGroundView)
backGroundView.heightAnchor.constraint(equalToConstant: 500).isActive = true
let backGroundImage = UIImageView()
backGroundImage.translatesAutoresizingMaskIntoConstraints = false
backGroundView.translatesAutoresizingMaskIntoConstraints = false
backGroundImage.heightAnchor.constraint(equalToConstant: 300).isActive = true
backGroundImage.widthAnchor.constraint(equalToConstant: 320).isActive = true
backGroundImage.image = UIImage(named: "empty")
backGroundView.addSubview(backGroundImage)
backGroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
backGroundView.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
backGroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 20).isActive = true
restaurantMainTable.backgroundView = backGroundView
restaurantMainTable.backgroundView?.isHidden = true
//MARK:- Add constraints to table
self.restaurantMainTable.translatesAutoresizingMaskIntoConstraints = false
self.restaurantMainTable.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
self.restaurantMainTable.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
self.restaurantMainTable.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
self.restaurantMainTable.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
//MARK:- register RestaurantMainViewCells
self.restaurantMainTable.register(RestaurantMainViewCells.self, forCellReuseIdentifier: String(describing: RestaurantMainViewCells.self))
//MARK:- Get fetch request
let fetchRequest: NSFetchRequest<Restaurant> = Restaurant.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
let context = appDelegate.persistentContainer.viewContext
fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchResultController.delegate = self
do {
try fetchResultController.performFetch()
if let fetchObject = fetchResultController.fetchedObjects {
restaurants = fetchObject
}
}
catch {
print(error)
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
restaurantMainTable.rowHeight = UITableView.automaticDimension
switch indexPath.row {
case 0:
let cell = restaurantMainTable.dequeueReusableCell(withIdentifier: String(describing: RestaurantMainViewCells.self), for: indexPath) as! RestaurantMainViewCells
// cell.heightAnchor.constraint(greaterThanOrEqualToConstant: 60).isActive = true
view.addSubview(cell)
view.addSubview(cell.contentView)
view.addSubview(cell.restaurantName)
view.addSubview(cell.restaurantType)
view.addSubview(cell.restaurantLocation)
view.addSubview(cell.restaurantMiniImage)
view.addSubview(cell.restaurantHeartImage)
cell.restaurantHeartImage.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantMiniImage.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantName.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantLocation.translatesAutoresizingMaskIntoConstraints = false
cell.restaurantType.translatesAutoresizingMaskIntoConstraints = false
//Fonts
let font = UIFont(name: "Rubik-Medium", size: 18)
let fontMetrics = UIFontMetrics(forTextStyle: .body)
let labels = [cell.restaurantName, cell.restaurantLocation, cell.restaurantType]
labels.forEach { label in
label.font = fontMetrics.scaledFont(for: font!)
}
let stackLabels = UIStackView()
view.addSubview(stackLabels)
stackLabels.alignment = .top
stackLabels.distribution = .fill
stackLabels.spacing = 5
stackLabels.axis = .vertical
stackLabels.addArrangedSubview(cell.restaurantName)
stackLabels.addArrangedSubview(cell.restaurantType)
stackLabels.addArrangedSubview(cell.restaurantLocation)
let stackImage = UIStackView()
view.addSubview(stackImage)
stackLabels.translatesAutoresizingMaskIntoConstraints = false
stackImage.alignment = .top
stackImage.distribution = .fill
stackImage.axis = .horizontal
stackImage.spacing = 5
cell.restaurantMiniImage.heightAnchor.constraint(equalToConstant: 60).isActive = true
cell.restaurantMiniImage.widthAnchor.constraint(equalToConstant: 60).isActive = true
cell.restaurantMiniImage.layer.cornerRadius = 30
cell.restaurantMiniImage.clipsToBounds = true
cell.restaurantHeartImage.heightAnchor.constraint(equalToConstant: 20).isActive = true
cell.restaurantHeartImage.widthAnchor.constraint(equalToConstant: 20).isActive = true
cell.restaurantHeartImage.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -10).isActive = true
cell.restaurantHeartImage.topAnchor.constraint(equalTo: cell.topAnchor, constant: 20).isActive = true
stackImage.addArrangedSubview(cell.restaurantMiniImage)
stackImage.addArrangedSubview(stackLabels)
view.addSubview(stackImage)
stackImage.translatesAutoresizingMaskIntoConstraints = false
stackImage.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 10).isActive = true
stackImage.topAnchor.constraint(greaterThanOrEqualTo: cell.topAnchor, constant: 10).isActive = true
// stackImage.topAnchor.constraint(equalTo: cell.topAnchor, constant: 10).isActive = true
stackImage.trailingAnchor.constraint(equalTo: cell.restaurantHeartImage.leadingAnchor, constant: -10).isActive = true
// stackImage.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: -10).isActive = true
stackImage.bottomAnchor.constraint(greaterThanOrEqualTo: cell.bottomAnchor, constant: -10).isActive = true
cell.restaurantName.text = restaurants[indexPath.row].name
cell.restaurantType.text = restaurants[indexPath.row].type
cell.restaurantLocation.text = restaurants[indexPath.row].location
cell.restaurantHeartImage.image = UIImage(named: "heart-tick")
if let restaurantImage = restaurants[indexPath.row].image {
cell.restaurantMiniImage.image = UIImage(data: restaurantImage as Data)
}
return cell
default:
fatalError("no data found")
}
}
//MARK:- Make custom navigation bar large font size and use rubik fonts
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationBar.topItem?.title = "LaViva Hotel"
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.hidesBarsOnSwipe = true
if let customFont = UIFont(name: "Rubik-Medium", size: 40) {
navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(red: 200/255, green: 70/255, blue: 70/255, alpha: 1), NSAttributedString.Key.font: customFont]
}
//MARK:- for empty table
if restaurants.count > 0 {
self.restaurantMainTable.backgroundView?.isHidden = true
self.restaurantMainTable.separatorStyle = .singleLine
}
else {
self.restaurantMainTable.backgroundView?.isHidden = false
self.restaurantMainTable.separatorStyle = .none
}
//MARK:- make an + button appear on top left
let addButton = UIBarButtonItem(image: UIImage(named: "plus"), style: .plain, target: self, action: #selector(addNewRestaurant))
//navigationController?.navigationItem.rightBarButtonItem = addButton
self.navigationItem.rightBarButtonItem = addButton
}
//MARK:- addNewRestaurant function
#objc func addNewRestaurant() {
let pushController = RestaurantAddController()
navigationController?.pushViewController(pushController, animated: true)
}
//MARK:- try and show cell and tower as default or dark done here
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
//add update delete
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
restaurantMainTable.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
if let newIndexPath = newIndexPath {
restaurantMainTable.insertRows(at: [newIndexPath], with: .fade)
}
case .delete:
if let indexPath = indexPath {
restaurantMainTable.deleteRows(at: [indexPath], with: .fade)
}
case .update:
if let indexPath = indexPath {
restaurantMainTable.reloadRows(at: [indexPath], with: .fade)
}
default:
restaurantMainTable.reloadData()
}
if let fetchedObjects = controller.fetchedObjects {
restaurants = fetchedObjects as! [Restaurant]
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
restaurantMainTable.endUpdates()
}
//MARK:- left swipr delete
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, view, completionHandler) in
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
let context = appDelegate.persistentContainer.viewContext
let restaurantsToDelete = self.fetchResultController.object(at: indexPath)
context.delete(restaurantsToDelete)
appDelegate.saveContext()
}
completionHandler(true)
}
let swipeConfiguration: UISwipeActionsConfiguration
swipeConfiguration = UISwipeActionsConfiguration(actions: [deleteAction])
return swipeConfiguration
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
UPDATE
import UIKit
class RestaurantMainViewCells: UITableViewCell {
var restaurantMiniImage = UIImageView()
var restaurantHeartImage = UIImageView()
var restaurantName = UILabel()
var restaurantType = UILabel()
var restaurantLocation = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
All of your cell setup - adding and constraining UI elements - should be done in your cell class. Absolutely NOT in cellForRowAt.
You would do well to go through a few tutorials on creating dynamic cells.
But, to give you an idea, here is your code modified so you can see what's happening:
struct Restaurant {
var name: String = ""
var type: String = ""
var location: String = ""
// however you have your image information stored
//var image
}
class RestaurantMainViewCells: UITableViewCell {
var restaurantMiniImage = UIImageView()
var restaurantHeartImage = UIImageView()
var restaurantName = UILabel()
var restaurantType = UILabel()
var restaurantLocation = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func commonInit() -> Void {
// so we can see the image view frames without actual images...
restaurantMiniImage.backgroundColor = .green
restaurantHeartImage.backgroundColor = .red
var font: UIFont = UIFont.systemFont(ofSize: 18)
if let f = UIFont(name: "Rubik-Medium", size: 18) {
font = f
}
let fontMetrics = UIFontMetrics(forTextStyle: .body)
let labels = [restaurantName, restaurantLocation, restaurantType]
labels.forEach { label in
label.font = fontMetrics.scaledFont(for: font)
// so we can see label frames...
label.backgroundColor = .yellow
}
let stackLabels = UIStackView()
stackLabels.alignment = .fill
stackLabels.distribution = .fill
stackLabels.spacing = 5
stackLabels.axis = .vertical
stackLabels.addArrangedSubview(restaurantName)
stackLabels.addArrangedSubview(restaurantType)
stackLabels.addArrangedSubview(restaurantLocation)
let stackImage = UIStackView()
stackImage.alignment = .top
stackImage.distribution = .fill
stackImage.axis = .horizontal
stackImage.spacing = 5
restaurantMiniImage.layer.cornerRadius = 30
restaurantMiniImage.clipsToBounds = true
stackImage.addArrangedSubview(restaurantMiniImage)
stackImage.addArrangedSubview(stackLabels)
contentView.addSubview(stackImage)
contentView.addSubview(restaurantHeartImage)
restaurantHeartImage.translatesAutoresizingMaskIntoConstraints = false
stackImage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// mini image 60x60
restaurantMiniImage.heightAnchor.constraint(equalToConstant: 60),
restaurantMiniImage.widthAnchor.constraint(equalToConstant: 60),
// heart image 20 x 20
restaurantHeartImage.heightAnchor.constraint(equalToConstant: 20),
restaurantHeartImage.widthAnchor.constraint(equalToConstant: 20),
// heart image top+20 trailing-10
restaurantHeartImage.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20),
restaurantHeartImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),
// horizontal stack top / leading / bottom and trailinh to heart image
// all with 10-pts "padding"
stackImage.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
stackImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
stackImage.trailingAnchor.constraint(equalTo: restaurantHeartImage.leadingAnchor, constant: -10),
stackImage.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
])
}
}
class RestaurantMainController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var restaurants: [Restaurant] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurants.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
let restaurantMainTable = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(restaurantMainTable)
//MARK:- add delegates as self, always, else no contact with model will take place
restaurantMainTable.estimatedRowHeight = 60
self.restaurantMainTable.delegate = self
self.restaurantMainTable.dataSource = self
self.restaurantMainTable.separatorStyle = .singleLine
//MARK:- Add constraints to table
self.restaurantMainTable.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
restaurantMainTable.topAnchor.constraint(equalTo: view.topAnchor),
restaurantMainTable.bottomAnchor.constraint(equalTo: view.bottomAnchor),
restaurantMainTable.leadingAnchor.constraint(equalTo: view.leadingAnchor),
restaurantMainTable.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
//MARK:- register RestaurantMainViewCells
self.restaurantMainTable.register(RestaurantMainViewCells.self, forCellReuseIdentifier: String(describing: RestaurantMainViewCells.self))
//MARK:- Get fetch request
// I don't have your "fetch" data, so I'm just adding a couple restaurants here
restaurants.append(Restaurant(name: "Cafe De Loir", type: "Chinese Cousine", location: "Hong Kong"))
restaurants.append(Restaurant(name: "Bob's Cafe", type: "Japanese Cousine", location: "Tokyo"))
restaurants.append(Restaurant(name: "Mary's Restaurant", type: "Home Cooking", location: "Dallas, Texas"))
// let fetchRequest: NSFetchRequest<Restaurant> = Restaurant.fetchRequest()
// let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
// fetchRequest.sortDescriptors = [sortDescriptor]
//
// if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
// let context = appDelegate.persistentContainer.viewContext
// fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
// fetchResultController.delegate = self
//
// do {
// try fetchResultController.performFetch()
// if let fetchObject = fetchResultController.fetchedObjects {
// restaurants = fetchObject
// }
// }
//
// catch {
// print(error)
// }
// }
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RestaurantMainViewCells.self), for: indexPath) as! RestaurantMainViewCells
let r = restaurants[indexPath.row]
cell.restaurantName.text = r.name
cell.restaurantType.text = r.type
cell.restaurantLocation.text = r.location
//if let restaurantImage = restaurants[indexPath.row].image {
// cell.restaurantMiniImage.image = UIImage(data: restaurantImage as Data)
//}
cell.restaurantHeartImage.image = UIImage(named: "heart-tick")
return cell
}
}
The result (I don't have your images so the image views have green or red background color):

TableView dynamic height problem inside a Cell

I have a tableView in tableViewCell with dynamic height together with other ui components having dynamic height & proportinal width to the cell. Problem: inner tableViewCells shrinks when rendered & scrolling outer uitableview. Here is the code:
import UIKit
import WebKit
import SVProgressHUD
class DashboardProgramcell: UITableViewCell, UITableViewDataSource, UITableViewDelegate{
Data, models here..
public var icerikModel:WMPIcerikModel?
static let ID:String = "DashboardProgramcell"
static let turCellPair = (tur: TurID.Program, cellId: ID)
var kListData: WMPArrayOfKatilimciModel?
Cell subViews..
//MainContainer
var container: UIView = {
var container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
return container
}()
//Left side
var leftContainer: UIView = {
var leftContainer = UIView()
leftContainer.translatesAutoresizingMaskIntoConstraints = false
return leftContainer
}()
var gSaat: UILabel = {
var gSaat = UILabel()
gSaat.translatesAutoresizingMaskIntoConstraints = false
gSaat.numberOfLines = 0
gSaat.font = UIFont.systemFont(ofSize: 11)
return gSaat
}()
var sure: UILabel = {
var sure = UILabel()
sure.translatesAutoresizingMaskIntoConstraints = false
sure.numberOfLines = 0
sure.backgroundColor = ColorHelper.mercury
sure.textAlignment = .center
sure.font = UIFont.systemFont(ofSize: 11)
return sure
}()
var ptad: UITextView = {
var ptad = UITextView()
ptad.textColor = .white
ptad.textAlignment = .center
ptad.isUserInteractionEnabled = false
ptad.isScrollEnabled = false
ptad.translatesAutoresizingMaskIntoConstraints = false
ptad.font = UIFont.systemFont(ofSize: 11)
ptad.textContainerInset = UIEdgeInsets.zero
ptad.textContainer.lineFragmentPadding = 0
return ptad
}()
//Right part
var rightContainer: UIView = {
var rightContainer = UIView()
rightContainer.translatesAutoresizingMaskIntoConstraints = false
return rightContainer
}()
var rightTopTextView: UILabel = {
var rightTopTextView = UILabel()
rightTopTextView.translatesAutoresizingMaskIntoConstraints = false
rightTopTextView.numberOfLines = 0
rightTopTextView.lineBreakMode = NSLineBreakMode.byWordWrapping
rightTopTextView.font = UIFont.systemFont(ofSize: 12)
rightTopTextView.backgroundColor = ColorHelper.arzPopup
return rightTopTextView
}()
Here is the inner tableView and its constraints!
var kList: UITableView = {
var kList = UITableView()
kList.contentMode = .scaleAspectFit
kList.bounces = false
kList.bouncesZoom = false
kList.alwaysBounceVertical = false
kList.translatesAutoresizingMaskIntoConstraints = false
kList.tag = KListCell.TAG
kList.rowHeight = UITableView.automaticDimension
kList.estimatedRowHeight = UITableView.automaticDimension
kList.register(KListCell.self, forCellReuseIdentifier: KListCell.ID)
kList.tableFooterView = UIView(frame: .zero)
return kList
}()
var kListHeightConstraint:NSLayoutConstraint?
var rTopTextViewHeightConstraint:NSLayoutConstraint?
Constructor & constraint activation!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.tag = TurID.Program.rawValue
self.selectionStyle = .none
self.addSubview(container)
container.addSubview(leftContainer) //OK
container.addSubview(rightContainer) //OK
leftContainer.addSubview(gSaat) //OK
leftContainer.addSubview(sure) //OK
leftContainer.addSubview(ptad)
rightContainer.addSubview(rightTopTextView)
rightContainer.addSubview(kList)
NSLayoutConstraint.activate([
container.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 2),
container.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -2),
container.topAnchor.constraint(equalTo: self.topAnchor, constant: 2),
container.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -2),
leftContainer.topAnchor.constraint(equalTo: container.topAnchor),
leftContainer.leftAnchor.constraint(equalTo: container.leftAnchor),
leftContainer.bottomAnchor.constraint(equalTo: container.bottomAnchor),
leftContainer.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.30),
leftContainer.heightAnchor.constraint(equalTo: container.heightAnchor),
leftContainer.rightAnchor.constraint(equalTo: rightContainer.leftAnchor),
rightContainer.topAnchor.constraint(equalTo: container.topAnchor),
rightContainer.bottomAnchor.constraint(equalTo: container.bottomAnchor),
rightContainer.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.68),
rightContainer.heightAnchor.constraint(equalTo: container.heightAnchor),
rightContainer.rightAnchor.constraint(equalTo: container.rightAnchor),
gSaat.topAnchor.constraint(equalTo: leftContainer.topAnchor, constant: 4),
gSaat.leftAnchor.constraint(equalTo: leftContainer.leftAnchor, constant: 4),
gSaat.rightAnchor.constraint(equalTo: leftContainer.rightAnchor, constant: -4),
gSaat.bottomAnchor.constraint(equalTo: sure.topAnchor, constant: -2),
sure.leftAnchor.constraint(equalTo: leftContainer.leftAnchor, constant: 4),
sure.rightAnchor.constraint(equalTo: leftContainer.rightAnchor, constant: -4),
sure.bottomAnchor.constraint(equalTo: ptad.topAnchor, constant:-2),
ptad.leftAnchor.constraint(equalTo: leftContainer.leftAnchor, constant: 4),
ptad.rightAnchor.constraint(equalTo: leftContainer.rightAnchor),
ptad.bottomAnchor.constraint(lessThanOrEqualTo: leftContainer.bottomAnchor),
ptad.heightAnchor.constraint(equalToConstant: 16),
rightTopTextView.topAnchor.constraint(equalTo: rightContainer.topAnchor, constant:4),
rightTopTextView.leftAnchor.constraint(equalTo: rightContainer.leftAnchor, constant:4),
rightTopTextView.rightAnchor.constraint(equalTo: rightContainer.rightAnchor, constant:-4),
rightTopTextView.bottomAnchor.constraint(equalTo: kList.topAnchor),
kList.leftAnchor.constraint(equalTo: rightContainer.leftAnchor, constant:2),
kList.rightAnchor.constraint(equalTo: rightContainer.rightAnchor, constant:-2),
kList.bottomAnchor.constraint(equalTo: rightContainer.bottomAnchor, constant:-2)
])
container.addBorders(edges: [.left, .right, .bottom], color: ColorHelper.programBg, width: 1)
kList.dataSource = self
kList.delegate = self
// kListHeightConstraint = kList.heightAnchor.constraint(equalToConstant: 150)
// kListHeightConstraint?.isActive = true
// rTopTextViewHeightConstraint = rightTopTextView.heightAnchor.constraint(equalToConstant: 120)
// rTopTextViewHeightConstraint?.isActive = true
self.rightTopTextView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapItself)))
self.layoutIfNeeded()
}
#objc func tapItself()
{
SVProgressHUD.show()
DispatchQueue.global(qos: .background).async {
SoapService(vc: self.viewControllerForTableView!).KayitDetay(tur: self.icerikModel!.TID!, kayitID: self.icerikModel!.ID!)
}
}
override func layoutSubviews()
{
super.layoutSubviews()
}
public func adjustSubViews()
{
DispatchQueue.main.async {
if let icerik = self.icerikModel {
//Left
self.gSaat.text = icerik.GSaat ?? ""
self.sure.text = icerik.Sure ?? ""
self.ptad.text = icerik.PTAD ?? ""
self.ptad.backgroundColor = self.ptad.text.isEmpty ? UIColor.clear : (self.ptad.text.hasPrefix("Arz") || self.ptad.text.hasPrefix("arz") ? TurID.Arz.tableviewBg() : TurID.Ziyaret.tableviewBg())
//Right
if let ack = icerik.Ack
{
self.rightTopTextView.attributedText = ack.convertHTML().convertHtmlAttributed()
// self.rTopTextViewHeightConstraint?.constant = self.rightTopTextView.contentSize.height
}
else
{
self.rightTopTextView.heightAnchor.constraint(equalToConstant: 0).isActive = true
}
if let KListe = icerik.KListe, KListe.count != 0 {
self.kListData = KListe
self.kList.reloadData()
}
else
{
// self.kListHeightConstraint?.constant = 5
SVProgressHUD.dismissMainUI { }
}
self.layoutIfNeeded()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let _kListData = self.kListData, _kListData.count != 0 {
return _kListData.count
}
return 0
}
var kTVHeight:CGFloat = 0
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let kListCell = tableView.dequeueReusableCell(withIdentifier: KListCell.ID) as! KListCell
if let _kListData = self.kListData , _kListData.count != 0 {
kListCell.katilimciModel = _kListData[indexPath.row]
kListCell.adjustSubViews()
// self.kTVHeight += kListCell.frame.height
if indexPath.row == _kListData.count - 1 && kTVHeight > 10
{
// kListHeightConstraint?.constant = kTVHeight
// rTopTextViewHeightConstraint?.constant = rightTopTextView.contentSize.height
// kTVHeight = 0
}
}
return kListCell
}
//If we got cell to display this func will work!
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.visibleCells.count == 0 {
SVProgressHUD.dismissMainUI { }
}
}
}//class DashboardProgramcell
class KListCell: UITableViewCell {
var katilimciModel:WMPKatilimciModel?
static let ID:String = "KListCell"
static let TAG = 4001
//MainContainer
var container: UIView = {
var container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
return container
}()
//Left side
var leftContainer: UIView = {
var leftContainer = UIView()
leftContainer.translatesAutoresizingMaskIntoConstraints = false
return leftContainer
}()
//Right part
var rightContainer: UIView = {
var rightContainer = UIView()
rightContainer.translatesAutoresizingMaskIntoConstraints = false
return rightContainer
}()
var adSoyad: UILabel = {
var adSoyad = UILabel()
adSoyad.translatesAutoresizingMaskIntoConstraints = false
adSoyad.numberOfLines = 0
adSoyad.font = UIFont.systemFont(ofSize: 10)
return adSoyad
}()
var unvan: UILabel = {
var unvan = UILabel()
unvan.translatesAutoresizingMaskIntoConstraints = false
unvan.numberOfLines = 0
unvan.font = UIFont.systemFont(ofSize: 10)
return unvan
}()
var userImage: UIImageView = {
var userImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 12, height: 12))
userImage.translatesAutoresizingMaskIntoConstraints = false
return userImage
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(container)
container.addSubview(leftContainer) //OK
container.addSubview(rightContainer) //OK
leftContainer.addSubview(userImage) //OK
rightContainer.addSubview(adSoyad)
rightContainer.addSubview(unvan)
self.applyConstraints()
}
override func layoutSubviews()
{
super.layoutSubviews()
}
func applyConstraints()
{
NSLayoutConstraint.activate([
container.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 2),
container.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -2),
container.topAnchor.constraint(equalTo: self.topAnchor, constant: 2),
container.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -2),
leftContainer.topAnchor.constraint(equalTo: container.topAnchor),
leftContainer.leftAnchor.constraint(equalTo: container.leftAnchor),
leftContainer.bottomAnchor.constraint(equalTo: container.bottomAnchor),
leftContainer.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.12),
leftContainer.heightAnchor.constraint(equalTo: container.heightAnchor),
leftContainer.rightAnchor.constraint(equalTo: rightContainer.leftAnchor),
rightContainer.topAnchor.constraint(equalTo: container.topAnchor),
rightContainer.bottomAnchor.constraint(equalTo: container.bottomAnchor),
rightContainer.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.86),
rightContainer.heightAnchor.constraint(equalTo: container.heightAnchor),
rightContainer.rightAnchor.constraint(equalTo: container.rightAnchor),
userImage.topAnchor.constraint(equalTo: leftContainer.topAnchor, constant:2),
userImage.heightAnchor.constraint(equalToConstant: 12),
userImage.widthAnchor.constraint(equalToConstant: 12),
userImage.centerXAnchor.constraint(equalTo: leftContainer.centerXAnchor),
userImage.bottomAnchor.constraint(lessThanOrEqualTo: leftContainer.bottomAnchor),
adSoyad.topAnchor.constraint(equalTo: rightContainer.topAnchor, constant: 2),
adSoyad.leftAnchor.constraint(equalTo: rightContainer.leftAnchor, constant: 2),
adSoyad.rightAnchor.constraint(equalTo: rightContainer.rightAnchor, constant: -2),
adSoyad.bottomAnchor.constraint(equalTo: unvan.topAnchor),
unvan.leftAnchor.constraint(equalTo: rightContainer.leftAnchor, constant: 2),
unvan.rightAnchor.constraint(equalTo: rightContainer.rightAnchor, constant: -2),
unvan.bottomAnchor.constraint(equalTo: rightContainer.bottomAnchor, constant: -2),
])
}
public func adjustSubViews ()
{
DispatchQueue.main.async {
if let katilimci = self.katilimciModel {
self.adSoyad.text = katilimci.AD ?? ""
self.unvan.text = katilimci.Ack ?? ""
self.userImage.image = UIImage(named:"userBlack")
}
}
}
}
Firstly change this code:
self.addSubview(container)
to
contentView.addSubview(container)
Views in cell should be added to contentView since it is root layout.

How to properly configure UITableView custom cell

I am trying to create a custom cell for my UITableView, but whether I use the cell with the identifier from storyboard, or completely create my own cell, for some reason the data loads but it only 1 cell when I scroll. It only shows 1 cell one at a time. Here is how I am currently trying to do it:
let cell = UITableViewCell()
let cellTextLabel = UILabel()
let cellDetailLabel = UILabel()
let imageView = UIImageView()
let phImage = UIImage(named: "CryptiXJustX")
func configureCustomCell() {
cell.addSubview(imageView)
imageView.backgroundColor = .clear
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
imageView.leftAnchor.constraint(equalTo: cell.leftAnchor, constant: 10).isActive = true
imageView.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
cell.addSubview(cellTextLabel)
cellTextLabel.translatesAutoresizingMaskIntoConstraints = false
cellTextLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
cellTextLabel.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
cellTextLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 10).isActive = true
cellTextLabel.textColor = .white
cell.addSubview(cellDetailLabel)
cellDetailLabel.translatesAutoresizingMaskIntoConstraints = false
cellDetailLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
cellDetailLabel.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
cellDetailLabel.topAnchor.constraint(equalTo: cellTextLabel.bottomAnchor, constant: 10).isActive = true
cellDetailLabel.textColor = .white
cellDetailLabel.font = cellDetailLabel.font.withSize(12)
cellDetailLabel.numberOfLines = 3
cell.backgroundColor = .clear
cell.textLabel?.textColor = .white
cell.detailTextLabel?.textColor = .white
imageView.image = phImage
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var index = indexPath.row
if contentData.count > 0 {
cellTextLabel.text = contentData[index].title
cellDetailLabel.text = contentData[index].text
return cell
} else {
return cell
}
}
I configureCustomCell() in ViewDidLoad(), I feel it has something to do with cellforRowAt method but I am not sure.
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
configureCustomCell()
NewsAPI.shared.getData(arr: true) { (success) in
DispatchQueue.main.async {
self.contentData = NewsAPI.shared.contentData[0].posts
self.tableView.reloadData()
}
}
}
Thank you.
Create the custom UITableViewCell as below
class CustomCell: UITableViewCell {
}
And in controller viewDidLoad you will register the above cell as below
tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "CustomCell")
The reason is because you are using on single instance cell for the whole tableview. This is an incorrect way to load your data into your UITableView
But you can try use instead of:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var index = indexPath.row
if contentData.count > 0 {
cellTextLabel.text = contentData[index].title
cellDetailLabel.text = contentData[index].text
return cell
} else {
return cell
}
}
Try to use like this way:
class MyCell: UITableViewCell {
let cellTextLabel = UILabel()
let cellDetailLabel = UILabel()
let imageView = UIImageView()
let phImage = UIImage(named: "CryptiXJustX")
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(imageView)
imageView.backgroundColor = .clear
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true
imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
contentView.addSubview(cellTextLabel)
cellTextLabel.translatesAutoresizingMaskIntoConstraints = false
cellTextLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
cellTextLabel.rightAnchor.constraint(equalTo: contentView.contentView.rightAnchor, constant: -10).isActive = true
cellTextLabel.topAnchor.constraint(equalTo: contentView.contentView.topAnchor, constant: 10).isActive = true
cellTextLabel.textColor = .white
contentView.addSubview(cellDetailLabel)
cellDetailLabel.translatesAutoresizingMaskIntoConstraints = false
cellDetailLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
cellDetailLabel.rightAnchor.constraint(equalTo: contentView.contentView.rightAnchor, constant: -10).isActive = true
cellDetailLabel.topAnchor.constraint(equalTo: cellTextLabel.bottomAnchor, constant: 10).isActive = true
cellDetailLabel.textColor = .white
cellDetailLabel.font = cellDetailLabel.font.withSize(12)
cellDetailLabel.numberOfLines = 3
contentView.backgroundColor = .clear
contentView.textLabel?.textColor = .white
contentView.detailTextLabel?.textColor = .white
}
}
On you ViewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
// if you are not using storyboard, make sure you are registered the cell ID
self.tableView!.register("CellID", forCellReuseIdentifier: tableReuseIdentifier)
}
Finally:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: 'CellID', for: indexPath) as! MyCell
cell.imageView.image = phImage
cell.cellTextLabel.text = contentData[indexPath.row].title
cell.cellDetailLabel.text = contentData[indexPath.row].text
return cell
}

Swift bool data not passed to tableview cell

I have a tableview that gets the data from an API. There is a isUnlocked variable that is also getting value from the API.
But besides the title and picture, the isUnlocked variable still has the default value set in the custom tableview class.
I pass the value in cellForRow function like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if tableView.tag == 1 {
let c = tableView.dequeueReusableCell(withIdentifier: CourseViewIdentifiers.courses.rawValue, for: indexPath) as! CourseViewTableViewCell
c.isUnlocked = tableData[indexPath.row].unlocked
c.selectionStyle = .none
c.courseTitle.text = tableData[indexPath.row].title
c.courseImage.loadImageFrom(urlString: tableData[indexPath.row].pic)
cell = c
}
return cell
}
And this is the custom class for tableview cell:
public var isUnlocked: Bool = false
private lazy var backView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
view.layer.cornerRadius = 5
view.layer.borderColor = UIColor.lightGray.cgColor
view.layer.borderWidth = 0.5
return view
}()
public lazy var courseImage: WebImageloader = {
let imv = WebImageloader()
imv.contentMode = .scaleAspectFill
return imv
}()
public lazy var courseTitle: UILabel = {
let label = UILabel()
label.font = UIFont.iransans(size: 18)
label.textAlignment = .right
return label
}()
private lazy var courseButton1: UIButton = {
let button = UIButton(type: .system)
if !isUnlocked {
button.setBackgroundImage(#imageLiteral(resourceName: "locked"), for: .normal)
button.isEnabled = false
}else{
button.setBackgroundImage(#imageLiteral(resourceName: "play"), for: .normal)
}
return button
}()
private lazy var courseButton2: UIButton = {
let button = UIButton(type: .system)
button.setBackgroundImage(#imageLiteral(resourceName: "download"), for: .normal)
return button
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: CourseViewIdentifiers.courses.rawValue)
print(isUnlocked,"***************")
setupUI()
contentView.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
private func setupUI() {
backView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(backView)
backView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 15).isActive = true
backView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
backView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 5).isActive = true
backView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5).isActive = true
backView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true
courseImage.translatesAutoresizingMaskIntoConstraints = false
backView.addSubview(courseImage)
courseImage.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -10).isActive = true
courseImage.centerYAnchor.constraint(equalTo: backView.centerYAnchor).isActive = true
courseImage.heightAnchor.constraint(equalToConstant: 50).isActive = true
courseImage.widthAnchor.constraint(equalToConstant: 50).isActive = true
courseImage.layer.cornerRadius = 25
courseImage.clipsToBounds = true
courseButton1.translatesAutoresizingMaskIntoConstraints = false
backView.addSubview(courseButton1)
courseButton1.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 10).isActive = true
courseButton1.centerYAnchor.constraint(equalTo: backView.centerYAnchor).isActive = true
courseButton1.heightAnchor.constraint(equalToConstant: 30).isActive = true
courseButton1.widthAnchor.constraint(equalToConstant: 30).isActive = true
courseButton1.layer.cornerRadius = 15
courseButton1.clipsToBounds = true
if isUnlocked {
courseButton2.translatesAutoresizingMaskIntoConstraints = false
backView.addSubview(courseButton2)
courseButton2.leftAnchor.constraint(equalTo: courseButton1.rightAnchor, constant: 10).isActive = true
courseButton2.centerYAnchor.constraint(equalTo: backView.centerYAnchor).isActive = true
courseButton2.heightAnchor.constraint(equalToConstant: 30).isActive = true
courseButton2.widthAnchor.constraint(equalToConstant: 30).isActive = true
courseButton2.layer.cornerRadius = 15
courseButton2.clipsToBounds = true
}
courseTitle.translatesAutoresizingMaskIntoConstraints = false
backView.addSubview(courseTitle)
courseTitle.rightAnchor.constraint(equalTo: courseImage.leftAnchor, constant: -10).isActive = true
courseTitle.topAnchor.constraint(equalTo: courseImage.topAnchor).isActive = true
courseTitle.leftAnchor.constraint(equalTo: courseButton1.rightAnchor, constant: 10)
}
The isUnlocked variable has the default False value no matter what I set it in the cellForRow function. Guys it's killing me please help.
I think your value is being set, but your UI is not being updated because it only gets set during initialization, where obviously the value of the Bool will always be the default value (false). So instead of calling setUpUI() in init(), call it after dequeue-ing.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if tableView.tag == 1 {
let c = tableView.dequeueReusableCell(withIdentifier: CourseViewIdentifiers.courses.rawValue, for: indexPath) as! CourseViewTableViewCell
c.isUnlocked = tableData[indexPath.row].unlocked
c.selectionStyle = .none
c.courseTitle.text = tableData[indexPath.row].title
c.courseImage.loadImageFrom(urlString: tableData[indexPath.row].pic)
c.setUpUI()
//print(c.isUnlocked)
cell = c
}
return cell
}
Or atleast move the set up of courseButton2 to another method and call that method.
Problem solved by adding this block of code:
DispatchQueue.main.async {
if DownloadManager.isDownloading(url: self.course_url!) {
self.courseButton2.alpha = 0.5
self.courseButton2.isEnabled = false
}
}
Just add this code to the cell, and your ok to go!

Resources