首页 > 解决方案 > 我需要在快速动态创建的单元格之间添加一个空格

问题描述

这是我的结构,里面我从 url 下载了一个 Json

    var bikes = [BikeStats]()

这是我关于表格视图的声明

    @IBOutlet weak var tableView: UITableView!

这是我用 n 创建表格视图的代码。行

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

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
    let imgURL = NSURL(string: "my_url/\(bikes[indexPath.row].Immagine)")
    if imgURL != nil{
        let data = NSData(contentsOf: (imgURL as URL?)!)
        cell.imageView?.image = UIImage(data: data! as Data)?.renderResizedImage(newWidth: 70)
    }

    cell.textLabel?.text = "\(bikes[indexPath.row].StatoBici.uppercased())"
    cell.backgroundColor = UIColor.darkGray
    cell.layer.borderColor = UIColor.darkGray.cgColor
    cell.textLabel?.textColor = UIColor.white
    tableView.separatorStyle = UITableViewCellSeparatorStyle.none

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? BikeDetailViewController {
        destination.bike = bikes[(tableView.indexPathForSelectedRow?.row)!]  
    }
}

我需要在动态创建的单元格之间添加一个空格。

标签: swiftuitableview

解决方案


如果您想要单元格之间的空白行,您需要增加行数并将交替单元格配置为空白而不是填充内容。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return bikes.count * 2
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)

    // affect only the even numbered cells (0, 2, 4, 6, 8 etc.)
    if indexPath.row % 2 == 0 {
        cell.imageView?.image = nil
        cell.textLabel?.text = ""
        // set the colors to whatever you want
        cell.backgroundColor = UIColor.darkGray
        cell.layer.borderColor = UIColor.darkGray.cgColor
        cell.textLabel?.textColor = UIColor.white
        return cell
    }

    let dataIndex = indexPath.row / 2 // we need to do this because we're doubling the number of rows

    let imgURL = NSURL(string: "my_url/\(bikes[dataIndex].Immagine)")
    if imgURL != nil{
        let data = NSData(contentsOf: (imgURL as URL?)!)
        cell.imageView?.image = UIImage(data: data! as Data)?.renderResizedImage(newWidth: 70)
    }

    cell.textLabel?.text = "\(bikes[dataIndex].StatoBici.uppercased())"
    cell.backgroundColor = UIColor.darkGray
    cell.layer.borderColor = UIColor.darkGray.cgColor
    cell.textLabel?.textColor = UIColor.white
    tableView.separatorStyle = UITableViewCellSeparatorStyle.none

    return cell
}

推荐阅读