Can't reverse table view - ios

I tried to reverse my table view in the view did load method by reversing the arrays but it's not working. I'm trying to make it so that it sorts the feed from the time it was created from top to bottom. Am I doing it wrong? If so what should I do?
class Feed: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
#IBOutlet var feedBar: UINavigationBar!
var titles = [String]()
var messages = [String]()
var usernames = [String]()
var types = [String]()
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
messages.reverse()
titles.reverse()
usernames.reverse()
types.reverse()
}
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
override func viewDidAppear(animated: Bool) {
println("View appeared")
self.messages.removeAll(keepCapacity: true)
self.titles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
self.types.removeAll(keepCapacity: true)
var postQuery = PFQuery(className: "Post")
postQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"] as! String)
self.titles.append(object["title"] as! String)
self.usernames.append(object["username"] as! String)
self.types.append(object["type"] as! String)
self.table.reloadData()
}
}
})
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let postCell = tableView.dequeueReusableCellWithIdentifier("feedPost", forIndexPath: indexPath) as! PostCell
var post = PFObject(className: "Post")
if messages.isEmpty == false {
postCell.message.text = messages[indexPath.row]
}
if titles.isEmpty == false {
postCell.postTtitle.text = titles[indexPath.row]
}
if usernames.isEmpty == false {
postCell.posterName.setTitle(usernames[indexPath.row], forState: .Normal)
}
if self.types[indexPath.row] == "post1" {
postCell.sideLeft.backgroundColor = self.UIColorFromRGB(0xFCFFBD)
postCell.sideRight.backgroundColor = self.UIColorFromRGB(0xFCFFBD)
} else if self.types[indexPath.row] == "post2" {
postCell.sideLeft.backgroundColor = self.UIColorFromRGB(0xFFB4AC)
postCell.sideRight.backgroundColor = self.UIColorFromRGB(0xFFB4AC)
} else if self.types[indexPath.row] == "post3" {
postCell.sideLeft.backgroundColor = self.UIColorFromRGB(0xFFD5A4)
postCell.sideRight.backgroundColor = self.UIColorFromRGB(0xFFD5A4)
}
postCell.selectionStyle = .None
postCell.message.scrollRangeToVisible(NSMakeRange(0, 0))
return postCell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usernames.count
}
}

Observe that in the view's life cycle the viewDidAppear gets called after your viewDidLoad method. It appears that you try to reload the contents from within your viewDidAppear method, and there you are clearing those arrays which you had reversed earlier in viewDidLoad. This is the reason why you are not seeing any effect. You might want to reverse your arrays there.

You are reversing array in viewDidLoad, but you append something in viewDidAppear. viewDidAppear call after viewDidLoad. You should reverse array in the end of viewDidAppear before call self.table.reloadData()
override func viewDidAppear(animated: Bool) {
println("View appeared")
self.messages.removeAll(keepCapacity: true)
self.titles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
self.types.removeAll(keepCapacity: true)
var postQuery = PFQuery(className: "Post")
postQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"] as! String)
self.titles.append(object["title"] as! String)
self.usernames.append(object["username"] as! String)
self.types.append(object["type"] as! String)
}
messages.reverse()
titles.reverse()
usernames.reverse()
types.reverse()
self.table.reloadData()
}
})
}

I figured it out what I did was I did this instead of append...
self.messages.insert(object["message"] as! String, atIndex: 0)
What this basically does is appends the newest message to the beginning of the array.

Related

indexPath.row not getting data from the array

I've created a PFQuery to get some strings from my parse server and the put this in a couple of arrays
var packsAvailable = [""]
var packsImage = [""]
var packsDescription = [""]
If I print the value of the array in the for loop of the query I get all the values in a proper array. However when I try and use this information to populate my collection view nothing happens. I can't figure this out because it works with the manually created arrays tableImages and tableData that I have commented out for testing.
import UIKit
import Parse
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
//var tableData: [String] = ["Tis is a description", "Test 22", "Test 33"]
//var tableImages: [String] = ["walk1bg", "2", "walk3bg"]
var packsAvailable = [""] // the total packs in the app
var packsImage = [""]
var packsDescription = [""]
override func viewDidLoad() {
super.viewDidLoad()
let packQuery = PFQuery(className: "Pack")
packQuery.findObjectsInBackground(block: { (objectsArray, error) in
if error != nil {
print(error!)
} else if let packs = objectsArray {
self.packsAvailable.removeAll() // remove them incase they double up
print(packs.count)
for object in packs {
/*
print(object["packName"])
print(object["packImage"])
print(object["packDesctription"])
*/
self.packsAvailable.append(object["packName"] as! String)
self.packsImage.append(object["packImage"] as! String)
self.packsDescription.append(object["packDesctription"] as! String)
/*
print(self.packsAvailable)
print(self.packsImage)
print(self.packsDescription)
*/
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return packsAvailable.count
}
func UIColorFromHEX(hexValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hexValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
//cell.labelCell.text = tableData[indexPath.row]
//cell.imageCell.image = UIImage(named: tableImages[indexPath.row])
cell.labelCell.text = packsDescription[indexPath.row]
print(packsDescription[indexPath.row])
cell.imageCell.image = UIImage(named: packsImage[indexPath.row])
cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height/2
cell.imageCell.layer.borderWidth = 3
cell.imageCell.layer.borderColor = UIColorFromHEX(hexValue: 0x62aca2).cgColor
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Selected \(indexPath.row)")
}
}
add collectionView.reloadData() after the for-in loop is completed inside your closure. This will tell your collectionView to fetch the current array values.
You forgot to reload the collectionView when the response comes from the server. just add collectionView.reloadData() after completion of for loop
override func viewDidLoad() {
super.viewDidLoad()
let packQuery = PFQuery(className: "Pack")
packQuery.findObjectsInBackground(block: { (objectsArray, error) in
if error != nil {
print(error!)
} else if let packs = objectsArray {
self.packsAvailable.removeAll() // remove them incase they double up
print(packs.count)
for object in packs {
/*
print(object["packName"])
print(object["packImage"])
print(object["packDesctription"])
*/
self.packsAvailable.append(object["packName"] as! String)
self.packsImage.append(object["packImage"] as! String)
self.packsDescription.append(object["packDesctription"] as! String)
/*
print(self.packsAvailable)
print(self.packsImage)
print(self.packsDescription)
*/
}
//swift 2.3
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
//swift 3
/* DispatchQueue.main.async {
self.collectionView.reloadData()
}*/
}
})
}

Retrieving Image, String and Int from Parse

I have to retrieve images from Parse, and I am working on this code:
class ViewControllerHome: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var MessageTable: UITableView!
let color = UIColor(red: 0.0/255.0, green: 105.0/255.0, blue: 92.0/255.0, alpha: 1)
let colore = UIColor.whiteColor()
let coloree = UIColor(red: 33.0/255.0, green: 33.0/255.0, blue: 33.0/255.0, alpha: 1)
var Username = [String]()
var Image = [PFFile]()
var Likes = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
var refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: Selector("refreshPulled"), forControlEvents: UIControlEvents.ValueChanged)
loadData()
self.MessageTable.reloadData()
self.navigationController?.navigationBar.barTintColor = color
self.navigationController?.navigationBar.tintColor = colore
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: colore]
UITabBar.appearance().barTintColor = coloree
UITabBar.appearance().tintColor = colore
UITabBar.appearance().translucent = false
self.MessageTable.delegate = self
self.MessageTable.dataSource = self
func refreshPulled() {
loadData()
self.MessageTable.reloadData()
refreshControl.endRefreshing()
}
}
func loadData() {
let query = PFQuery(className: "Messages")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(posts: [PFObject]?, error: NSError?) -> Void in
if (error == nil) {
if let posts = posts as [PFObject]? {
for post in posts{
self.Image.append(post["Post"] as! PFFile)
self.Username.append(post["Name"] as! String)
self.Likes.append(post["Vote"] as! Int)
}
}
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.MessageTable.dequeueReusableCellWithIdentifier("cell")! as! TableViewCellHome
var imagesToLoad = self.Image[indexPath.row] as PFFile
var imagesUser = self.Username[indexPath.row] as String
var imageLikes = self.Likes[indexPath.row] as Int
//This line gives me an error: call can throw, but is not marked with 'try' and the error is not handled
var imagesdata = imagesToLoad.getData()
var finalizedImage = UIImage(data: imagesdata)
cell.PostImage.image = finalizedImage
cell.UsernameLabel.text = imagesUser
cell.LikesLabel.text = "\(imageLikes)"
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Username.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
This code should get and display Image, string and Int Value from parse's backend. The problem is that nothing is displayed. How can I change the code so that this will display correctly? There is also an error at the line:
var imagesdata = imagesToLoad.getData()
This line tells me
call can throw, but is not marked with 'try' and the error is not handled
Thanks in advance to anyone that can help me solve this problem.

Table view scrolling is erratic and jumpy even though I reuse cells?

Okay, so I'm not sure whats been happening with my Table view, but it seems to act a bit strange now that I load images from parse onto it. At first, it ran smoothly, but now that I'm working in ios 9, the scrolling is horrible
Optimizations I've used to reduce this(Keep in mind they do not really help.)
-Removed transparent objects and set them to default background
-reused table cells
-Tried to use lower quality images
Here is my code
import UIKit
class mainVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var resultsTable: UITableView!
#IBOutlet weak var menuButton:UIBarButtonItem!
var deleteArray = [String]()
var followArray = [String]()
var resultsLocationArray = [String]()
var datetextfielArray = [String]()
var imageDates = [String]()
var resultsNameArray = [String]()
var resulltsImageFiles = [PFFile]()
var resultsTweetArray = [String]()
var resultsHasImageArray = [String]()
var resultsTweetImageFiles = [PFFile?]()
var refresher:UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
// Uncomment to change the width of menu
//self.revealViewController().rearViewRevealWidth = 62
}
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0, 0, theWidth, theHeight)
let tweetBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: Selector("tweetBtn_click"))
let searchBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: Selector("searchBtn_click"))
let buttonArray = NSArray(objects: tweetBtn, searchBtn)
self.navigationItem.rightBarButtonItems = buttonArray as? [UIBarButtonItem]
refresher = UIRefreshControl()
refresher.tintColor = UIColor.blackColor()
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.resultsTable.addSubview(refresher)
}
func refresh() {
print("refresh table")
refreshResults()
}
func refreshResults() {
followArray.removeAll(keepCapacity: false)
resultsNameArray.removeAll(keepCapacity: false)
resulltsImageFiles.removeAll(keepCapacity: false)
resultsTweetArray.removeAll(keepCapacity: false)
resultsLocationArray.removeAll(keepCapacity: false)
resultsHasImageArray.removeAll(keepCapacity: false)
resultsTweetImageFiles.removeAll(keepCapacity: false)
datetextfielArray.removeAll(keepCapacity: false)
let followQuery = PFQuery(className: "follow")
followQuery.whereKey("user", equalTo: PFUser.currentUser()!.username!)
followQuery.addDescendingOrder("createdAt")
let objects = followQuery.findObjects()
for object in objects! {
self.followArray.append(object.objectForKey("userToFollow") as! String)
}
let query:PFQuery = PFQuery(className: "tweets")
query.whereKey("userName", containedIn: followArray)
query.addDescendingOrder("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resulltsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsTweetArray.append(object.objectForKey("tweet") as! String)
//resultsLocationArray
self.resultsLocationArray.append(object.objectForKey("tweetlocation") as! String)
self.resultsHasImageArray.append(object.objectForKey("hasImage") as! String)
self.resultsTweetImageFiles.append(object.objectForKey("tweetImage") as? PFFile)
self.datetextfielArray.append(object.objectForKey("datetextfield") as! String)
self.resultsTable.reloadData()
}
self.refresher.endRefreshing()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = false
super.viewWillAppear(animated)
let nav = self.navigationController?.navigationBar
nav?.barStyle = UIBarStyle.Black
nav?.tintColor = UIColor.whiteColor()
nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationItem.hidesBackButton = true
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func viewDidAppear(animated: Bool) {
refreshResults()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsNameArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if resultsHasImageArray[indexPath.row] == "yes" {
return self.view.frame.size.width + 130
} else {
return 130
}
}
//var theDtS = dtFormater.stringFromDate(self.dateArray[i])
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:mainCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! mainCell
cell.tweetImg.hidden = true
cell.locationTxt.text = self.resultsLocationArray[indexPath.row]
cell.profileLbl.text = self.resultsNameArray[indexPath.row]
cell.messageTxt.text = self.resultsTweetArray[indexPath.row]
cell.datetextfield.text = self.datetextfielArray[indexPath.row]
resulltsImageFiles[indexPath.row].getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
//resultsLocationArray
if error == nil {
let image = UIImage(data: imageData!)
cell.imgView.image = image
}
}
if resultsHasImageArray[indexPath.row] == "yes" {
let theWidth = view.frame.size.width
cell.tweetImg.frame = CGRectMake(0, 0, theWidth, theWidth)
cell.tweetImg.hidden = false
resultsTweetImageFiles[indexPath.row]?.getDataInBackgroundWithBlock({
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.tweetImg.image = image
}
})
}
return cell
}
func tweetBtn_click() {
print("tweet pressed")
self.performSegueWithIdentifier("gotoTweetVCFromMainVC", sender: self)
}
func searchBtn_click() {
print("search pressed")
self.performSegueWithIdentifier("gotoUsersVCFromMainVC", sender: self)
}
}

Two custom cells in UITableView

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,

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