Two custom cells in UITableView - ios

I'm trying to use two custom cells for displaying the product information, on the first one I show the product main information and in the second one I display the comments of this product.
At the moment everything is linked in the StoryBoard and I have my tableview prepared for storing the comment information in the second custom cell (I have checked the requestComments() function and It's working fine but I can't make them appear.
Is it something related to the numberOfRowsInSection? Because I tried to SUM the products.count with the comments.count and It's showing an error.
It's my first time using two custom cells so I hope someone can help me.
Here is my code:
import UIKit
import Social
class MarcaProductoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var productoImageView:UIImageView!
#IBOutlet var tableView:UITableView!
#IBOutlet var votarFrame:UIView!
#IBOutlet var votarBarra:UISlider!
#IBOutlet var votarLabel:UILabel!
var productoImage:String!
var nombre:String!
var producto:Producto!
var productos = [Producto]()
var mensaje:Mensaje!
var mensajes = [Mensaje]()
var img:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
// Set table view background color
self.tableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.2)
// Remove extra separator
self.tableView.tableFooterView = UIView(frame: CGRectZero)
// Change separator color
self.tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0
requestPost()
requestComments()
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func requestPost () {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.website.es/product.php")!)
request.HTTPMethod = "POST"
let postString = "name="+name
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
self.productos = self.parseJsonData(data!)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
task.resume()
tableView.reloadData()
}
func parseJsonData(data: NSData) -> [Producto] {
var productos = [Producto]()
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
// Parse JSON data
let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
for jsonProducto in jsonProductos {
let producto = Producto()
producto.image = jsonProducto["image"] as! String
producto.name = jsonProducto["name"] as! String
producto.desc = jsonProducto["desc"] as! String
productos.append(producto)
}
}
catch let parseError {
print(parseError)
}
return productos
}
func requestComments () {
//print("Hola")
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.website.es/comments.php")!)
request.HTTPMethod = "POST"
let postString = "name="+name
//print(postString)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print("mensajes = \(responseString)")
self.mensajes = self.parseJsonDataComments(data!)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
task.resume()
tableView.reloadData()
}
func parseJsonDataComments(data: NSData) -> [Mensaje] {
var messages = [Mensaje]()
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
// Parse JSON data
let jsonProductos = jsonResult?["messages"] as! [AnyObject]
for jsonProducto in jsonProductos {
let message = Mensaje()
message.author = jsonProducto["author"] as! String
message.message = jsonProducto["message"] as! String
message.date = jsonProducto["date"] as! String
messages.append(message)
}
}
catch let parseError {
print(parseError)
}
return message
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return productos.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
title = productos[indexPath.row].nombre
if indexPath.row == 0 {
print("11")
let cell = tableView.dequeueReusableCellWithIdentifier("CellDetail", forIndexPath: indexPath) as! ProductoTableViewCell
cell.selectionStyle = .None
if let url = NSURL(string: productos[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
self.productoImageView.image = UIImage(data: data)
}
}
cell.name.text = productos[indexPath.row].name
cell.desc.text = productos[indexPath.row].desc
cell.layoutIfNeeded()
return cell
}
else {
print("22")
let cell2 = tableView.dequeueReusableCellWithIdentifier("MostrarComentarios", forIndexPath: indexPath) as! ComentariosTableViewCell
cell2.selectionStyle = .None
cell2.author.text = mensajes[indexPath.row].author
cell2.comment.text = mensajes[indexPath.row].comments
cell2.date.text = mensajes[indexPath.row].date
cell2.layoutIfNeeded()
return cell2
}
} }
Update:
I have made the following changes:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return productos.count+mensajes.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return productos.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
title = productos[indexPath.row].nombre
if indexPath.section == 0 {
print("11")
let cell = tableView.dequeueReusableCellWithIdentifier("CellDetail", forIndexPath: indexPath) as! ProductoTableViewCell
cell.selectionStyle = .None
if let url = NSURL(string: productos[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
self.productoImageView.image = UIImage(data: data)
}
}
cell.nombre.text = productos[indexPath.row].nombre
cell.descripcion.text = productos[indexPath.row].descripcion
cell.modo_de_empleo.text = productos[indexPath.row].modo_de_empleo
cell.marca.text = productos[indexPath.row].marca
cell.linea.text = productos[indexPath.row].linea
cell.distribuidor.text = productos[indexPath.row].distribuidor
cell.tamano.text = productos[indexPath.row].tamano
cell.precio.text = productos[indexPath.row].precio
cell.codigo_nacional.text = productos[indexPath.row].codigo_nacional
cell.layoutIfNeeded()
return cell
}
else {
let cell2 = tableView.dequeueReusableCellWithIdentifier("MostrarComentarios", forIndexPath: indexPath) as! ComentariosTableViewCell
print(mensajes[indexPath.row].mensaje)
cell2.selectionStyle = .None
cell2.comentario.text = mensajes[indexPath.row].mensaje
cell2.fecha.text = mensajes[indexPath.row].fecha
cell2.layoutIfNeeded()
return cell2
}
}
At the moment, I can display the comments perfectly, but the problem is that the messages from this product are always the same (repeated in every new comment row) I just need to change something (I don't know what exactly) to show the correct information for the messages without beeing duplicated.
Thanks in advance.

I think you have to use return products.count
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return products.count
}
And you have to use % 2 == 0 instead of == 0
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
title = productos[indexPath.row].nombre
if indexPath.row % 2 == 0 { // runs if indexPath.row = 0, 2, 4, 6 etc
let cell = tableView.dequeueReusableCellWithIdentifier("CellDetail", forIndexPath: indexPath) as! ProductoTableViewCell
return cell
} else { // runs if indexPath.row = 1, 3, 5, 7 etc
let cell2 = tableView.dequeueReusableCellWithIdentifier("MostrarComentarios", forIndexPath: indexPath) as! ComentariosTableViewCell
return cell2
}
}
Remainder Operator
The remainder operator (a % b) works out how many multiples of b will
fit inside a and returns the value that is left over (known as the
remainder).
Here’s how the remainder operator works. To calculate 9 % 4, you first
work out how many 4s will fit inside 9:
You can fit two 4s inside 9, and the remainder is 1 (shown in orange).
In Swift, this would be written as:
9 % 4 // equals 1

If someone has the same problem:
else {
let cell2 = tableView.dequeueReusableCellWithIdentifier("MostrarComentarios", forIndexPath: indexPath) as! ComentariosTableViewCell
cell2.selectionStyle = .None
cell2.comentario.text = mensajes[(indexPath.section)-1].mensaje
cell2.fecha.text = mensajes[(indexPath.section)-1].fecha
cell2.layoutIfNeeded()
return cell2
}
Regards,

Related

how to update the UITableView data while scrolling

I have displayed data in the UITableView.The listing is for add cart items in cart list.
According to this picture can see the following details:-
price
Name of product
Stepper to add the quantity
Total Amount
So for this Firstly I added the product in the UITableView. Then stepper action to increases or decreases the quantity, I given the code according .
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell: ChartCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? ChartCell
if cell == nil {
tableView.register(UINib(nibName: "ChartCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? ChartCell
}
cell.setEventData(carts: chartViewModel.datafordisplay(atindex: indexPath))
cell.cartadd = { [weak self] in
if let i = self?.tableView.indexPath(for: $0) {
let productid = self?.chartViewModel.datafordisplay(atindex: indexPath)
print(productid?.cartid)
self?.chartViewModel.search(idsearch:productid?.cartid)
print(self?.chartViewModel.searchindex(objectatindex: 0))
cell.setcartData(cartsadd: (self?.chartViewModel.searchindex(objectatindex:0))!)
print(cell.quantity)
self?.chartViewModel.totalPriceInCart()
let theIntegerValue1 :[Int] = (self?.chartViewModel.totalvalue)!
let result = "\(theIntegerValue1[0])"
print(result)
let theStringValue1 :String = String(describing: result)
print(theStringValue1)
self?.totalresult.text = theStringValue1
print(i)
}
}
the viewmodel:-
class ChartViewModel: NSObject {
var datasourceModel:ChartDataSourceModel
var totalvalue:[Int] = []
var insertedArray:CartModel?
var filteredListArray:Array<CartModel>? = []
var productArray:CartModel?
var finalListArray:Array<CartModel>? = []
init(withdatasource newDatasourceModel: ChartDataSourceModel) {
datasourceModel = newDatasourceModel
print(datasourceModel.dataListArray)
}
func search(idsearch :String?) {
filteredListArray = datasourceModel.dataListArray?.filter{($0.cartid?.range(of: idsearch!, options: .caseInsensitive) != nil)}
print(filteredListArray)
}
func searchindex(objectatindex index: Int) -> CartModel {
return self.filteredListArray![index]
}
func datafordisplay(atindex indexPath: IndexPath) -> CartModel{
return datasourceModel.dataListArray![indexPath.row]
}
func numberOfRowsInSection(section:Int) -> Int {
return datasourceModel.dataListArray!.count
}
func delete(atIndex indexPath: IndexPath) {
datasourceModel.dataListArray!.remove(at: indexPath.row)
print(datasourceModel.dataListArray)
}
func totalPriceInCart() {
var totalPrice: Int = 0
for product in datasourceModel.dataListArray! {
totalPrice += product.cartsumint!
print(totalPrice)
}
self.totalvalue = [totalPrice]
}
func insert(atIndex indexPath: IndexPath) {
print(productArray)
print(datasourceModel.dataListArray)
datasourceModel.dataListArray!.insert(productArray!, at: indexPath.row)
print(datasourceModel.dataListArray)
self.datasourceModel.dataListArray = datasourceModel.dataListArray
print(datasourceModel.dataListArray)
self.finalListArray = self.datasourceModel.dataListArray
}
func add() {
datasourceModel.dataListArray?.append(insertedArray!)
print(datasourceModel.dataListArray)
print(insertedArray?.offerAddName)
print(insertedArray?.offerprice)
self.datasourceModel.dataListArray = datasourceModel.dataListArray
print(insertedArray?.cartsum)
}
}
The above code is to add the quantity. And this code is given in UITableView cellForRowAt delegate.
But the problem is:-
-As i adding the quantity of product ,the price also changes And will display in the UITableView. But while scrolling the UITableView the data will show as before.That means :-
initial suppose:- product name : car, price: 300, quantity: 1
This will show at UITableView. When I added quantity: 2, So price: 600 this will show in the UITableView.
But the problem is while scrolling the UITableView it become as price: 300, quantity: 1.
So how to update the UITableView. what should do
The UITableviewCell:-
func setEventData(carts:QM_CartModel)
{
self.name.text = carts.cartname
self.price.text = carts.carttotalprice
self.itemQuantityStepper.value = 1
setItemQuantity(quantity)
print(self.price.text)
let value = carts.cartsum
let x: Int? = Int(value!)
print(x)
let add = x!
print(add)
let theIntegerValue1 :Int = add
let theStringValue1 :String = String(theIntegerValue1)
// self.price.text = theStringValue1
self.price.text = "QR \(theStringValue1)"
print(self.price.text)
}
func setcartData(cartsadd:QM_CartModel)
{
let theIntegerValue :Int = self.quantity
let theStringValue :String = String(theIntegerValue)
cartsadd.cartquantity = theStringValue
print(cartsadd.cartquantity)
print(cartsadd.cartsum)
let value = cartsadd.cartsum
let qty = cartsadd.cartquantity
let x: Int? = Int(value!)
print(x)
let y: Int? = Int(qty!)
print(y)
let add = x! * y!
print(add)
let theIntegerValue1 :Int = add
let theStringValue1 :String = String(theIntegerValue1)
// self.price.text = theStringValue1
self.price.text = "QR \(theStringValue1)"
print(self.price.text)
cartsadd.cartsumint = theIntegerValue1
// print(cartsadd.cartsum)
}
You need to store your data(updated) in your model class.Because while scrolling tableview dequeuereusablecell again call and it will get data from model that's why you always get old data.
class TableViewCellData {
var data: Any?
}
-
class TableViewCell: UITableViewCell {
var cellData: TableViewCellData?
{
didSet {
// change data in cell from TableViewCellData
}
}
var cartadd: (() -> Void)?
}
-
class ViewController: UITableViewController {
var dataSource: [TableViewCellData] = []
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! TableViewCell
cell.cellData = dataSource[indexPath.row]
cell.cartadd = {
cell.cellData?.data = "" // set data to TableViewCellData
}
return cell
}
}

Different cells in tableview swift 3

example [1]: https://i.stack.imgur.com/8cORc.png
how to make the following table correctly
I do not want crutches
All cells one by one, except for a block of X.count, there will be a different number (from two or more)
how to find out the first and last cells from Block X later to show or hide the strip between the cells (between the points, I make their three thin ones, and want to hide or show the cell depending on the cell)
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
class TableVC: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var loadingView: UIView!
var number: String! = "number"
var detail_data: DetailListData?
var token: String?
var json = "Invalid"
override func viewDidLoad() {
super.viewDidLoad()
loadingView.isHidden = false
print("===============================",number!)
tableView.register(UINib(nibName: "HeaderTVC", bundle: Bundle.main), forCellReuseIdentifier: "HeaderTVC")
tableView.register(UINib(nibName: "DistanceTVC", bundle: Bundle.main), forCellReuseIdentifier: "DistanceTVC")
tableView.register(UINib(nibName: "MapTVC", bundle: Bundle.main), forCellReuseIdentifier: "MapTVC")
tableView.register(UINib(nibName: "InfoTVC", bundle: Bundle.main), forCellReuseIdentifier: "InfoTVC")
tableView.register(UINib(nibName: "BottomTVC", bundle: Bundle.main), forCellReuseIdentifier: "BottomTVC")
tableView.delegate = self
token = UserDefaults.standard.value(forKey: "token")! as? String
getData()
}
func getData () {
let httpHeaders = ["Authorization": token!,
"Accept": "application/json"]
Alamofire.request(REST_API.MAIN_URL_DEV + REST_API.SHIPMENTS + "/" + number! ,encoding: JSONEncoding.default, headers: httpHeaders)
.responseString { response in
if let JSON = response.result.value {
self.json = JSON
// print(JSON)
if let jsonObj = self.json.parseJSONString {
if let data = jsonObj as? NSDictionary {
if let obj = DetailListJson4Swift_Base(dictionary: data) {
if obj.status?.code == 200 {
self.detail_data = obj.data
print("////==================== DATA", obj.data!, self.detail_data!)
self.loadingView.isHidden = true
self.tableView.reloadData()
} else {
print("Status: Error code")
MyAlertController.doAlert("Error", alertMessage: "something wrong, try again late")
}
} else {
MyAlertController.doAlert("Error", alertMessage: "Unable to construct movie object")
print("Unable to construct movie object")
}
} else {
MyAlertController.doAlert("Error", alertMessage: "Unable to interpret parsed object as dictionary")
print("Unable to interpret parsed object as dictionary")
print(jsonObj)
}
}
}
}
}
#IBAction func accept(_ sender: Any) {
}
}
extension TableVC {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if detail_data != nil {
if section == 0 {
return 3
} else if section == 1 {
return (detail_data?.waypoints?.count)!
} else if section == 2 {
return 1
}
}
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let headerTVC = tableView.dequeueReusableCell(withIdentifier: "HeaderTVC", for: indexPath) as! HeaderTVC
headerTVC.code.text = detail_data?.id!
headerTVC.price.text = detail_data?.price?.total!
headerTVC.distamce.text = detail_data?.distance!
return headerTVC
}
if indexPath.row == 1 {
let distanceTVC = tableView.dequeueReusableCell(withIdentifier: "DistanceTVC", for: indexPath) as! DistanceTVC
return distanceTVC
}
if indexPath.row == 2 {
let mapTVC = tableView.dequeueReusableCell(withIdentifier: "MapTVC", for: indexPath) as! MapTVC
return mapTVC
}
if indexPath.row == 4 {
let bottomTVC = tableView.dequeueReusableCell(withIdentifier: "BottomTVC", for: indexPath) as! BottomTVC
return bottomTVC
}
// the other cells should contains title and subtitle:
let infoTVC = tableView.dequeueReusableCell(withIdentifier: "InfoTVC", for: indexPath) as! InfoTVC
return infoTVC
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

Value in JSON does not display in tableviewcell custom

Can't display data in TableViewCell.Data reports of events, but the when you open the array "sports" display the data in cels no.The display of the title occurs and the transfer is ended...
This is my json code...
Event.swift
import UIKit
struct Event {
let match : String
let forecast : String
let data : String
let image : UIImage
var sports : [Sport]
init (match : String, forecast : String, data: String, image : UIImage, sports : [Sport]) {
self.match = match
self.forecast = forecast
self.data = data
self.image = image
self.sports = sports
}
static func eventsFromBundle ()-> [Event] {
var events = [Event] ()
guard let url = Bundle.main.url(forResource: "events", withExtension: "json") else {
return events
}
do {
let data = try Data(contentsOf: url)
guard let rootObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any] else {
return events
}
guard let eventObjects = rootObject["events"] as? [[String: AnyObject]] else {
return events
}
for eventObject in eventObjects {
if let match = eventObject["match"] as? String,
let forecast = eventObject["forecast"] as? String,
let data = eventObject["data"] as? String,
let imageName = eventObject["image"] as? String,
let image = UIImage(named: imageName),
let sportsObject = eventObject["sports"] as? [[String : String]]{
var sports = [Sport]()
for sportObject in sportsObject {
if let nameTitle = sportObject["name"] ,
let titleName = sportObject["image"],
let titleImage = UIImage(named: titleName + ".jpg"),
let prognozLabel = sportObject["prognoz"],
let obzor = sportObject["obzor"] {
sports.append(Sport(name: nameTitle, prognoz: prognozLabel, image: titleImage, obzor: obzor, isExpanded: false))
}
}
let event = Event(match: match, forecast: forecast, data: data, image: image, sports: sports)
events.append(event)
}
}
} catch {
return events
}
return events
}
}
import UIKit
class SportViewController: BaseViewController {
var events = Event.eventsFromBundle ()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange, object: .none, queue: OperationQueue.main) { [weak self] _ in
self?.tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SportDetailViewController,
let indexPath = tableView.indexPathForSelectedRow {
destination.selectedEvent = events[indexPath.row]
}
}
}
extension SportViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellMatch", for: indexPath) as! SportTableViewCell
let event = events[indexPath.row]
cell.matchLabel.text = event.match
cell.imageMatch.image = event.image
cell.forecastLabel.text = event.forecast
cell.dataLabel.text = event.data
cell.matchLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
cell.forecastLabel.font = UIFont.preferredFont(forTextStyle: .callout)
return cell
}
}
Her is the controller.SportDetailViewController.swift
import UIKit
class SportDetailViewController: UIViewController {
var selectedEvent : Event!
let obzorText = "Select for more info >"
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = selectedEvent.match
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
extension SportDetailViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return selectedEvent.sports.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : SportDetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellMatch", for: indexPath) as! SportDetailTableViewCell
let sport = selectedEvent.sports[indexPath.row]
cell.nameTitle.text = sport.name
cell.titleImage.image = sport.image
cell.prognozLabel.text = sport.prognoz
cell.selectionStyle = .none
cell.nameTitle.backgroundColor = UIColor.darkGray
cell.backgroundColor = UIColor.red
cell.obzorText.text = sport.isExpanded ? sport.obzor : obzorText
cell.obzorText.textAlignment = sport.isExpanded ? .left : .center
return cell
}
}
extension SportDetailViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? SportDetailTableViewCell else { return }
var sport = selectedEvent.sports[indexPath.row]
sport.isExpanded = !sport.isExpanded
selectedEvent.sports[indexPath.row] = sport
cell.obzorText.text = sport.isExpanded ? sport.obzor : obzorText
cell.obzorText.textAlignment = sport.isExpanded ? .left : .center
tableView.beginUpdates()
tableView.endUpdates()
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
all these methods have tried: tableview.datasource = self , tableview.delegate = self и reloadData().....in viewDidLoad.
Delete this init from your struct: (because struct gets free initializer)
init (match : String, forecast : String, data: String, image : UIImage, sports : [Sport]) {
self.match = match
self.forecast = forecast
self.data = data
self.image = image
self.sports = sports
}
Now, your var events won't be populated as you are calling method in class scope. So change this:
class SportViewController: BaseViewController {
var events = Event.eventsFromBundle ()
...
...
}
to
class SportViewController: BaseViewController {
var events = [Event]()
...
...
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
events = Event().eventsFromBundle()
}
...
...
}
This should solve your problem.

Why am I getting the error: fatal error: unexpectedly found nil while unwrapping an Optional value?

I have a TableViewController below that I am trying to populate with a query request from Parse. The idea is that the call (which I have checked and is returning the necessary information) then fills the arrays, which I then use to populate the TableViewCells. These cells also have a custom class ('TableViewCell').
For some reason, 'self.tableView.reloadData()' is definitely causing the crash. When I remove it, it doesn't crash but the tableviewcells don't update with the parse information. Any ideas?
import UIKit
import Parse
class AuctionViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "Cell")
}
var capArray = [String]()
var imageDic = [String: [PFFile]]()
var priceArray = [Int]()
override func viewDidAppear(animated: Bool) {
capArray.removeAll(keepCapacity: true)
imageDic.removeAll(keepCapacity: true)
priceArray.removeAll(keepCapacity: true)
let query = PFQuery(className: "SellerObject")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for o in objects {
if o.objectForKey("caption") != nil && o.objectForKey("imageFile") != nil && o.objectForKey("price") != nil {
let cap = o.objectForKey("caption") as? String
self.capArray.append(cap!)
let imdic = o.objectForKey("imageFile") as? [PFFile]
self.imageDic[cap!] = imdic
let price = o.objectForKey("price") as? String
let priceInt = Int(price!)
self.priceArray.append(priceInt!)
print(self.capArray)
print(self.imageDic)
print(self.priceArray)
}
self.tableView.reloadData()
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return capArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
cell.captionLabel.text = self.capArray[indexPath.row]
return cell
}
First of all, you are not checking cap, imdic, price by type. And reloading tableView many times in cycle. Replace
for o in objects {
if o.objectForKey("caption") != nil && o.objectForKey("imageFile") != nil && o.objectForKey("price") != nil {
let cap = o.objectForKey("caption") as? String
self.capArray.append(cap!)
let imdic = o.objectForKey("imageFile") as? [PFFile]
self.imageDic[cap!] = imdic
let price = o.objectForKey("price") as? String
let priceInt = Int(price!)
self.priceArray.append(priceInt!)
print(self.capArray)
print(self.imageDic)
print(self.priceArray)
}
self.tableView.reloadData()
}
with
for o in objects {
if let cap = o.objectForKey("caption") as? String,
let imdic = o.objectForKey("imageFile") as? [PFFile],
let priceInt = (o.objectForKey("price") as? String).flatMap({ Int($0))}) {
self.capArray.append(cap)
self.imageDic[cap] = imdic
self.priceArray.append(priceInt)
print(self.capArray)
print(self.imageDic)
print(self.priceArray)
}
}
self.tableView.reloadData()
Also, don't dequeue cell that way. Replace
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
cell.captionLabel.text = self.capArray[indexPath.row]
return cell
}
with
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? TableViewCell else {
assertionFailure("cell for index-path:\(indexPath) not found")
return UITableViewCell()
}
cell.captionLabel.text = self.capArray[indexPath.row]
return cell
}
But I think that problem could always be inside TableViewCell class🤔 For example, captionLabel could be nil.

UIView inside UIView with TextField and Button not working

Good afternoon,
I'm trying to show a UIView when (in my case) there isn't any result to show in a tableView filled with products. When I detect 0 products, I show a UIView which contains a Label, a TextField and a Button, but I can't interact with my TextField and neither with the Button.
It's my first time using this technique to show a UIView when something went wrong with the tableView so I would like to know what's wrong in my code and what I'm missing because it's really weird.
Here is my code (when I print "Product not found" is where I show the UIView):
import UIKit
import Social
class ProductoCamViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var productoImageView:UIImageView!
#IBOutlet var tableView:UITableView!
#IBOutlet weak var noEncontrado:UIView!
var productoImage:String!
var ean:String!
var producto:Producto!
var productos = [Producto]()
#IBOutlet weak var toolBar: UIToolbar!
#IBOutlet weak var cargando: UIActivityIndicatorView!
override func viewDidLoad() {
toolBar.hidden = true
noEncontrado.hidden = true
cargando.hidden = false
super.viewDidLoad()
// Set table view background color
self.tableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.2)
// Remove extra separator
self.tableView.tableFooterView = UIView(frame: CGRectZero)
// Change separator color
self.tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0
requestPost()
cargando.hidden = true
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func requestPost () {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.mywebsite.com/product.php")!)
request.HTTPMethod = "POST"
let postString = "ean="+ean
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// JSON RESULTADO ENTERO
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
if (responseString == "Product not found")
{
self.noEncontrado.hidden = false
self.tableView.reloadData()
return
}
else
{
self.productos = self.parseJsonData(data!)
self.toolBar.hidden = false
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
task.resume()
}
func parseJsonData(data: NSData) -> [Producto] {
var productos = [Producto]()
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
noEncontrado.hidden = true
// Parse JSON data
let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
for jsonProducto in jsonProductos {
let producto = Producto()
producto.imagen = jsonProducto["imagen"] as! String
producto.nombre = jsonProducto["nombre"] as! String
producto.descripcion = jsonProducto["descripcion"] as! String
producto.modo_de_empleo = jsonProducto["modo_de_empleo"] as! String
producto.marca = jsonProducto["marca"] as! String
producto.linea = jsonProducto["linea"] as! String
producto.distribuidor = jsonProducto["distribuidor"] as! String
producto.tamano = jsonProducto["tamano"] as! String
producto.precio = jsonProducto["precio"] as! String
producto.codigo_nacional = jsonProducto["codigo_nacional"] as! String
productos.append(producto)
}
}
catch let parseError {
print(parseError)
}
return productos
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return productos.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
title = productos[indexPath.row].nombre
let cell = tableView.dequeueReusableCellWithIdentifier("CellDetail", forIndexPath: indexPath) as! ProductoTableViewCell
cell.selectionStyle = .None
if let url = NSURL(string: productos[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
self.productoImageView.image = UIImage(data: data)
}
}
cell.nombre.text = productos[indexPath.row].nombre
cell.descripcion.text = productos[indexPath.row].descripcion
cell.modo_de_empleo.text = productos[indexPath.row].modo_de_empleo
cell.marca.text = productos[indexPath.row].marca
cell.linea.text = productos[indexPath.row].linea
cell.distribuidor.text = productos[indexPath.row].distribuidor
cell.tamano.text = productos[indexPath.row].tamano
cell.precio.text = productos[indexPath.row].precio
cell.codigo_nacional.text = productos[indexPath.row].codigo_nacional
cell.layoutIfNeeded()
return cell
}
}
Thanks in advance.
At first, please try to provide english code :) but anyways. I think the view what should appear is nonEncontrado.
There could be some issues but i need to see the storyboard.
The view has userInteraction not enabled. Its a property and can also be activated in the storyboard
The view is overlayed by something else. Maybe the empty tableView.
As an suggestion you could provide this fields in the tableView and just load another DataSource. Than you dont need to fight with extra views. If you provide screens from the Storyboard i could help a bit more.
Good Luck :)

Resources