2015-10-02 1 views
1

Я пытаюсь использовать две пользовательские ячейки для отображения информации о продукте, в первой из которых я показываю основную информацию о продукте, а во втором я показываю комментарии к этому продукту.Две пользовательские ячейки в UITableView

На данный момент все связано в StoryBoard, и у меня есть таблица, подготовленная для хранения информации о комментариях во второй пользовательской ячейке (я проверил функцию requestComments() и работает нормально, но я не могу заставить их отображаться .

Является ли это что-то связано с numberOfRowsInSection? Потому что я пытался просуммировать products.count с comments.count и он показывает ошибку.

это мой первый раз, используя два пользовательских ячеек, так что я надеюсь, кто-то может мне помочь.

Вот мой код:

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 
    } 
} } 

Обновление:

Я сделал следующие изменения:

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 
    } 
} 

На данный момент я могу отобразить комментарии отлично, но проблема в том, что сообщения из этого продукта всегда одинаковы (повторяются в каждой новой строке комментариев) Мне просто нужно что-то изменить (я не знаю, что именно), чтобы показать правильную информацию для сообщений без дублирования.

Заранее спасибо.

ответ

0

Если кто-то имеет такую ​​же проблему:

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 
    } 

С уважением,

1

Я думаю, вы должны использовать return products.count

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return products.count 
} 

И вы должны использовать % 2 == 0 вместо == 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 
    } 
} 

Оператора остатках

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:

enter image description here

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 
+0

Привет @Arsen, что именно "% 2"? С уважением. –

+0

Привет @Jordi! Это оператор остатка. Он позволяет запускать некоторый код для четных и нечетных элементов. – Arsen

+0

@ Jordi это полезно? – Arsen