Error 'get output frames failed, state 8196' whilst using Google Places API - ios

I have a searchController getting data from Google Places API. I am using a UITableView to populate the cells, however, they are not being populated (I assume due to the above error)
I have all the delegates set up
TableView is reloading data
The request is being printed in the console as expected
From what I have read on S/OF this could be something to do with the registration of the cell - see below code
TableView
func configureTableView() {
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor,
paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0,
width: 0, height: 0)
tableView.tableFooterView = UIView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: recentSearchesCellIdentifier)
tableView.register(ResultsCell.self, forCellReuseIdentifier: searchResultsCellIdentifier)
tableView.keyboardDismissMode = .interactive
tableView.backgroundColor = UIColor(red: 242/255, green: 242/255, blue: 243/255, alpha: 1)
}
CellForItemAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let recentSearchesCell = tableView.dequeueReusableCell(withIdentifier: recentSearchesCellIdentifier, for: indexPath)
let searchResultsCell = tableView.dequeueReusableCell(withIdentifier: searchResultsCellIdentifier, for: indexPath) as! ResultsCell
switch sections[indexPath.section].section {
case .RecentSearches:
recentSearchesCell.selectionStyle = .none
let recentSearches = recentResults[indexPath.row]
recentSearchesCell.textLabel?.text = recentSearches
recentSearchesCell.detailTextLabel?.text = recentSearches
return recentSearchesCell
case .SearchResults:
searchResultsCell.selectionStyle = .none
let result = searchResults[indexPath.row]
searchResultsCell.result = result
return searchResultsCell
}
}
Cell
class ResultsCell: UITableViewCell {
var result: GMSAutocompletePrediction? {
didSet {
self.textLabel?.attributedText = result?.attributedPrimaryText
self.detailTextLabel?.attributedText = result?.attributedSecondaryText
}
}
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
}
}

Related

Presenting UICollectionView from a UIButton swift

first, I hope I don't break any rules or make it long but I'm really stuck and spent the whole day about that so I would love to get help with that :).
Okay so I'm having a popped up view controller using Panmodel 3rd party and I've got a UIButton inside of a UITableView custom cell, now I want to present my custom calendar when the user press the button, now I followed Ray tutorial(Link) on how to do a custom calendar and it still doesn't work for me, for some reason when I press the button it just shows a clear view + freezes my screen :|, I'm going to post the code of my tableView setup + the cell of the UIButton, not going to post the code of the calendar because it's long and I don't want to spam, if needed I will post that :) once again thanks for the help really spent the whole day about it and found myself with no solution, so here's my code:
Code: TableViewVC:
import UIKit
import PanModal
class FilterTableViewController: UITableViewController, PanModalPresentable {
var panScrollable: UIScrollView? {
return tableView
}
var albumsPickerIndexPath: IndexPath? // indexPath of the currently shown albums picker in tableview.
var datesCell = DatesCell()
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
// registerTableViewCells()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// tableView.frame = view.bounds
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - View Configurations
func setupTableView() {
tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
tableView.separatorStyle = .singleLine
tableView.isScrollEnabled = false
tableView.allowsSelection = true
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 600
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
func indexPathToInsertDatePicker(indexPath: IndexPath) -> IndexPath {
if let albumsPickerIndexPath = albumsPickerIndexPath, albumsPickerIndexPath.row < indexPath.row {
return indexPath
} else {
return IndexPath(row: indexPath.row + 1, section: indexPath.section)
}
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// If datePicker is already present, we add one extra cell for that
if albumsPickerIndexPath != nil {
return 5 + 1
} else {
return 5
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let byActivityCell = UINib(nibName: "byActivityCell",bundle: nil)
self.tableView.register(byActivityCell,forCellReuseIdentifier: "byActivityCell")
let activityCell = tableView.dequeueReusableCell(withIdentifier: "byActivityCell", for: indexPath) as! byActivityCell
activityCell.selectionStyle = .none
return activityCell
case 1:
let byTypeCell = UINib(nibName: "ByType",bundle: nil)
self.tableView.register(byTypeCell,forCellReuseIdentifier: "byTypeCell")
let typeCell = tableView.dequeueReusableCell(withIdentifier: "byTypeCell", for: indexPath) as! ByType
typeCell.selectionStyle = .none
return typeCell
case 2:
let byHashtagsCell = UINib(nibName: "ByHashtags",bundle: nil)
self.tableView.register(byHashtagsCell,forCellReuseIdentifier: "byHashtagsCell")
let hashtagsCell = tableView.dequeueReusableCell(withIdentifier: "byHashtagsCell", for: indexPath) as! ByHashtags
hashtagsCell.selectionStyle = .none
return hashtagsCell
case 3:
let byDatesCell = UINib(nibName: "DatesCell",bundle: nil)
self.tableView.register(byDatesCell,forCellReuseIdentifier: "byDatesCell")
let datesCell = tableView.dequeueReusableCell(withIdentifier: "byDatesCell", for: indexPath) as! DatesCell
datesCell.selectionStyle = .none
datesCell.datesTableViewCellDelegate = self
return datesCell
case 4:
let byAlbumCell = UINib(nibName: "AlbumCell",bundle: nil)
self.tableView.register(byAlbumCell,forCellReuseIdentifier: "byAlbumCell")
let albumCell = tableView.dequeueReusableCell(withIdentifier: "byAlbumCell", for: indexPath) as! AlbumCell
albumCell.configureCell(choosenAlbum: "Any")
albumCell.selectionStyle = .none
return albumCell
case 5:
let albumPickerCell = UINib(nibName: "AlbumsPickerTableViewCell", bundle: nil)
self.tableView.register(albumPickerCell, forCellReuseIdentifier: "albumPickerCell")
let albumsPicker = tableView.dequeueReusableCell(withIdentifier: "albumPickerCell", for: indexPath) as! AlbumsPickerTableViewCell
return albumsPicker
default:
return UITableViewCell()
}
}
// MARK: - footer Methods:
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return getfooterView()
}
func getfooterView() -> UIView
{
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 400))
let applyFiltersBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 380, height: 35))
applyFiltersBtn.center = footerView.center
applyFiltersBtn.layer.cornerRadius = 12
applyFiltersBtn.layer.masksToBounds = true
applyFiltersBtn.setTitle("Apply Filters", for: .normal)
applyFiltersBtn.backgroundColor = #colorLiteral(red: 0.1957295239, green: 0.6059523225, blue: 0.960457623, alpha: 1)
// doneButton.addTarget(self, action: #selector(hello(sender:)), for: .touchUpInside)
footerView.addSubview(applyFiltersBtn)
return footerView
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
// MARK: TableViewDelegate Methods:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
tableView.beginUpdates()
// 1 - We Delete the UIPicker when the user "Deselect" the row.
if let datePickerIndexPath = albumsPickerIndexPath, datePickerIndexPath.row - 1 == indexPath.row {
tableView.deleteRows(at: [datePickerIndexPath], with: .fade)
self.albumsPickerIndexPath = nil
} else {
// 2
// if let datePickerIndexPath = albumsPickerIndexPath {
// tableView.deleteRows(at: [datePickerIndexPath], with: .fade)
// }
albumsPickerIndexPath = indexPathToInsertDatePicker(indexPath: indexPath)
tableView.insertRows(at: [albumsPickerIndexPath!], with: .fade)
tableView.deselectRow(at: indexPath, animated: true)
}
tableView.endUpdates()
if indexPath.row == 4 {
let pickerController = CalendarPickerViewController(
baseDate: Date(),
selectedDateChanged: { [weak self] date in
guard let self = self else { return }
// self.item.date = date
self.tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .fade)
})
present(pickerController, animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.row == 4 {
return indexPath
} else {
return nil
}
}
}
extension FilterTableViewController: DatesTableViewCellDelegate {
func didButtonFromPressed() {
print("Button From is Pressed")
let pickerController = CalendarPickerViewController(
baseDate: Date(),
selectedDateChanged: { [weak self] date in
guard let self = self else { return }
// self.item.date = date
self.tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .fade)
})
present(pickerController, animated: true, completion: nil)
}
func didButtonToPressed() {
print("Button To is Pressed")
//TODO: Present our custom calendar
let vcToDisplay = CalendarPickerViewController(baseDate: Date()) { (date) in
self.tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .fade)
}
self.present(vcToDisplay, animated: true, completion: nil)
}
}
custom cell code:
import UIKit
// MARK: - Class Protocols:
protocol DatesTableViewCellDelegate { // a delegate to tell when the user selected the button:
func didButtonFromPressed()
func didButtonToPressed()
}
class DatesCell: UITableViewCell {
#IBOutlet var fromDate: UIButton!
#IBOutlet var toDate: UIButton!
var datesTableViewCellDelegate: DatesTableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
fromDate.layer.cornerRadius = 5
toDate.layer.cornerRadius = 5
fromDate.layer.borderWidth = 1
toDate.layer.borderWidth = 1
fromDate.layer.borderColor = #colorLiteral(red: 0.2005972862, green: 0.6100016236, blue: 0.9602670074, alpha: 1)
toDate.layer.borderColor = #colorLiteral(red: 0.2005972862, green: 0.6100016236, blue: 0.9602670074, alpha: 1)
fromDate.layer.masksToBounds = true
toDate.layer.masksToBounds = true
self.preservesSuperviewLayoutMargins = false
self.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
self.layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
}
// MARK: - UIButton Methods:
#IBAction func fromDateButtonIsPressed(_ sender: UIButton) {
datesTableViewCellDelegate?.didButtonFromPressed()
}
#IBAction func toDateButtonIsPressed(_ sender: UIButton) {
datesTableViewCellDelegate?.didButtonToPressed()
}
}
Found the problem, the problem was with the auto-layout, I changed the auto layout to be like this:
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .yellow
view.addSubview(dimmedBackgroundView)
view.addSubview(collectionView)
var constraints = [
dimmedBackgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
dimmedBackgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
dimmedBackgroundView.topAnchor.constraint(equalTo: view.topAnchor),
dimmedBackgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]
constraints.append(contentsOf: [
//1
collectionView.leadingAnchor.constraint(
equalTo: view.readableContentGuide.leadingAnchor),
collectionView.trailingAnchor.constraint(
equalTo: view.readableContentGuide.trailingAnchor),
//2
collectionView.centerYAnchor.constraint(
equalTo: view.centerYAnchor,
constant: 10),
//3
collectionView.heightAnchor.constraint(
equalTo: view.heightAnchor,
multiplier: 0.5)
])
NSLayoutConstraint.activate(constraints)
// NSLayoutConstraint.activate([
// dimmedBackgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
// dimmedBackgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// dimmedBackgroundView.topAnchor.constraint(equalTo: view.topAnchor),
// dimmedBackgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
// ])
}

TableView inside UIView doesn't show up Swift

I’m having a problem with embedding tableView inside a UIView. I tell you what my goal is:
My goal is to have a little tableView with 3 rows (like here - Link), now I’ve made a custom UIView with a tableView inside but for some reason it doesn’t load my data + doesn’t show anything. I must be honest I’m not sure if it is the right way of doing that, cause maybe there’s a better way of doing that, so I hope you guys can help me out.
Here's my code:
import Foundation
import UIKit
class TypeTableView: UIView, UITableViewDataSource, UITableViewDelegate {
var typesData = ["Videos","Images","Posts"]
var tableView = UITableView()
// let screenHeight = UIScreen.main.bounds.height
// let screenWidth = UIScreen.main.bounds.width
//
override init(frame: CGRect){
super.init(frame: frame)
self.backgroundColor = .red
setup()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func setup() {
tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1000, height: 100),style: .grouped)
tableView.backgroundColor = .red
tableView.layer.cornerRadius = 10
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
self.addSubview(tableView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return typesData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
cell.textLabel?.text = typesData[indexPath.row]
return cell
}
}
Here's the custom cell of the tableView(the tableView is inside the customCell):
import UIKit
class ByType: UITableViewCell {
// var typesData = ["Videos","Images","Posts"]
#IBOutlet var groupedTableView: TypeTableView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// self.preservesSuperviewLayoutMargins = false
self.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
self.layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
groupedTableView.layer.cornerRadius = 5
groupedTableView.layer.masksToBounds = true;
groupedTableView.backgroundColor = .red
groupedTableView.layer.borderWidth = 0.5
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

Change Spacing of Cocoa Class TableViewCell in ViewController - Swift

I have searched for hours trying stackOverFlows solutions to this issue!!! All of which cause my custom UITable Cells to overlap and not space out. I just want my spacing to be automatic like 'return UITableView.automaticDimension' but say + 8 so that my custom cells aren't right next to each other. I cannot figure it out and maybe it is because I have one line of code that I shouldn't.
This is my cocoa touch class that creates my custom cell 'DiscussionTableViewCell':
class DiscussionTableViewCell: UITableViewCell {
lazy var backView: UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: UIScreen.main.bounds.width - 20, height: 55))
view.backgroundColor = UIColor.rgb(r: 194, g: 208, b: 242)
//view.layer.borderWidth = 3
return view
}()
lazy var discussionTitleLabel: UILabel = {
let LDiscussionTitleLabel = UILabel(frame: CGRect(x: 4, y: 6, width: backView.frame.width - 116, height: 30))
LDiscussionTitleLabel.textAlignment = .left
LDiscussionTitleLabel.font = UIFont.boldSystemFont(ofSize: 18)
return LDiscussionTitleLabel
}()
lazy var discussionDescriptionLabel: UILabel = {
let LDiscussionDescriptionLabel = UILabel(frame: CGRect(x: 4, y: 27, width: backView.frame.width - 30, height: 30))
LDiscussionDescriptionLabel.textAlignment = .left
LDiscussionDescriptionLabel.font = UIFont.systemFont(ofSize: 16)
LDiscussionDescriptionLabel.textColor = UIColor.gray
return LDiscussionDescriptionLabel
}()
override func awakeFromNib() {
super.awakeFromNib()
//layoutMargins = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
// Initialization code
}
override func layoutSubviews() {
//super.layoutSubviews()
contentView.backgroundColor = UIColor.rgb(r: 203, g: 215, b: 242)
backgroundColor = UIColor.yellow
backView.layer.cornerRadius = 5
backView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
addSubview(backView)
backView.addSubview(discussionTitleLabel)
backView.addSubview(discussionDescriptionLabel)
// Configure the view for the selected state
}
}
And a section of my ViewController that applies to assigning text to the table cell, and spacing between cells:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return discussionTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DiscussionTableViewCell
cell.discussionTitleLabel.text = discussionTitles[indexPath.row]
cell.discussionDescriptionLabel.text = discussionDescriptions[indexPath.row]
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (singlePageVar == 100) {
return 1407//UITableView.automaticDimension
}
return 62//UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("section: \(indexPath.section)")
print("row: \(indexPath.row)")
var topicNumberRow = (indexPath.row)
mainTopicNumberRow = topicNumberRow
DiscussionBoardTopicThread()
}
//function I call in viewdidload to show table
func setupDiscussionBoard() {
discussionBoardView.separatorStyle = .none
view.addSubview(discussionBoardView)
discussionBoardView.backgroundColor = UIColor(red: 203/255, green: 215/255, blue: 242/255, alpha: 1.0)
discussionBoardView.dataSource = self
discussionBoardView.delegate = self
discussionBoardView.translatesAutoresizingMaskIntoConstraints = false
discussionBoardView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
discussionBoardView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
discussionBoardView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
discussionBoardView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
discussionBoardView.register(DiscussionTableViewCell.self, forCellReuseIdentifier: "cell")
}
}

After update tableview did not work. Why is this happen?

I have interesting problem in my machine. I want to make table view and I did it many times but after the update its not working. Is the making way is changed or what? Can anyone help me?
Here my controller and delegate methods:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView = {
let tv = UITableView()
tv.separatorStyle = .none
tv.allowsSelection = false
return tv
}()
override func viewDidLoad() {
super.viewDidLoad()
titleOfapp ()
setupTableView()
}
let sipCellId = "sipCellId"
func titleOfapp () {
let titleLabelMarka = UILabel()
titleLabelMarka.textAlignment = .center
titleLabelMarka.text = "Pak Terminal"
titleLabelMarka.textColor = UIColor.white
titleLabelMarka.font = UIFont(name:"Comfortaa-bold", size: 24)
navigationItem.titleView = titleLabelMarka
navigationController?.navigationBar.barTintColor = UIColor.init(red: 80.0/255.0, green: 197.0/255.0, blue: 247.0/255.0, alpha: 1.0)
}
func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.register(sipCell.self, forCellReuseIdentifier: sipCellId)
view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: sipCellId, for: indexPath) as! sipCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
And here my custom cell code:
class sipCell: UITableViewCell {
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")
}
let cellView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
var detailLabel: UILabel = {
let tf = UILabel()
tf.text = "mehmet akyol"
tf.textColor = .black
tf.font = UIFont(name: "Comfortaa-Bold", size: 13)
return tf
}()
func setup(){
addSubview(cellView)
addSubview(detailLabel)
cellView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 4, paddingLeft: 8, paddingBottom: 4, paddingRight: 8, width: 60, height: 55)
detailLabel.anchor(top: nil, left: cellView.leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 8, paddingBottom: 4, paddingRight: 8, width: 60, height: 40)
detailLabel.centerYAnchor.constraint(equalTo: cellView.centerYAnchor).isActive = true
}
}
You need to create constraints for the table
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
])
or set a frame

Swift - Could not cast value of 'UITableViewCell'

I am attempting to create a very simple Table View containing images and labels. I am attempting to customize/style what the inside of each cell looks like (programattically), therefore I have created a class called "BarCell" in order to program how each cell should look. However, when I try to follow this format, I am getting the following error :
Could not cast value of type 'UITableViewCell' (0x10bda7038) to 'ProjectName.BarCell' (0x105332c38).
What does this error mean? I have declared my class of BarCell as a type of UITableViewCell. Therefore, how am I getting this error? Very new to swift, so any tips advise that could point me to the right direction will be extremely helpful. Here is my complete code
//
// HomeController.swift
// Covered
//
// Created by name on 1/3/18.
// Copyright © 2018 name. All rights reserved.
//
import UIKit
import Firebase
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource{
let bars = ["one", "two", "three"]
let tableView: UITableView = {
let tv = UITableView()
tv.separatorStyle = .none
tv.allowsSelection = true
return tv
}()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bars.count
}
var barImage: UIImage?
var barCover: String?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BarCell
cell.imageView?.image = UIImage(named: bars[indexPath.row])
cell.textLabel?.text = bars[indexPath.item]
barImage = cell.imageView?.image
barCover = cell.textLabel?.text
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 160
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func viewDidLoad() {
super.viewDidLoad()
setUpNavigationBar()
setUpTableView()
//user is not logged in
if Auth.auth().currentUser?.uid == nil {
perform(#selector(handleSignOut), with: nil, afterDelay: 0)
}
}
func setUpNavigationBar(){
navigationItem.title = "Covered"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
navigationItem.leftBarButtonItem?.tintColor = .black
}
func setUpTableView(){
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
_ = tableView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: view.frame.width, heightConstant: view.frame.height)
}
#objc func handleSignOut(){
do{
try Auth.auth().signOut()
} catch let logOutError{
print("Here is the log out error: /n")
print(logOutError)
}
//change state of user default
UserDefaults.standard.setIsLoggedIn(value: false)
//present login controller
let loginController = LoginController()
present(loginController, animated: true, completion: nil)
}
}
class BarCell: UITableViewCell{
let cellView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.dropShadow()
return view
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
func setup(){
addSubview(cellView)
_ = cellView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 4, leftConstant: 8, bottomConstant: 4, rightConstant: 8)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
My error is coming up at line 32, which is :
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BarCell
Any ideas why this is happening? My code runs well when i cast this line as! UITableViewCell directly. However, I am trying to do this in order to set the appearance for each cell. Thanks in advance for any advice.
The problem is that the lines:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
and
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BarCell
don't match.
If you really want the cell to have a type of BarCell then register a BarCell instead of s UITableViewCell.
tableView.register(BarCell.self, forCellReuseIdentifier: "cell")

Resources