【问题标题】:Two custom cells in UITableViewUITableView 中的两个自定义单元格
【发布时间】:2015-10-02 07:55:27
【问题描述】:

我正在尝试使用两个自定义单元格来显示产品信息,第一个显示产品主要信息,第二个显示该产品的 cmets。

目前,所有内容都已链接到 StoryBoard 中,并且我已准备好用于将评论信息存储在第二个自定义单元格中的表格视图(我已检查 requestComments() 函数,它工作正常,但我无法让它们出现。

是否与 numberOfRowsInSection 相关?因为我尝试将 products.count 与 cmets.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
    }
}

目前,我可以完美显示 cmets,但问题是来自此产品的消息始终相同(在每个新评论行中重复)我只需要更改一些内容(我不知道具体是什么) ) 以显示消息的正确信息而不会重复。

提前致谢。

【问题讨论】:

    标签: ios swift uitableview custom-cell


    【解决方案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
      }
    }
    

    余数运算符

    余数运算符 (a % b) 计算出 b 的倍数 适合 a 并返回剩余的值(称为 余数)。

    这是余数运算符的工作原理。要计算 9 % 4,您首先 计算出 9 中可以容纳多少个 4:

    9 内可以放两个 4,余数是 1(以橙色显示)。

    在 Swift 中,这会写成:

    9 % 4    // equals 1
    

    【讨论】:

    • 嗨@Arsen,“ % 2 ”到底是什么?问候。
    • 嗨@Jordi!它是余数运算符。它允许您为偶数和奇数元素运行一些代码
    • @Jordi 有帮助吗?
    • 嗨@Arsen,我试图改变一些与你的解决方案不同的东西,我将用这些改变来更新我的第一条消息,因为我几乎明白了,它只是我的消息中重复的内容。再次感谢。
    • 另外@Arsen,当我使用“return products.count + mensajes.count”时,它显示错误“致命错误:数组索引超出范围”。
    【解决方案2】:

    如果有人遇到同样的问题:

    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
        }
    

    问候,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      相关资源
      最近更新 更多