gpt4 book ai didi

ios - UITableViewCell 的动态维度可以,但是如果为空如何隐藏它们?

转载 作者:行者123 更新时间:2023-11-28 21:40:31 26 4
gpt4 key购买 nike

我有一个包含 3 个原型(prototype)单元格的 UITableView(例如第一个单元格:图像,第二个单元格:描述,3. 链接,...)。

如果后端的数据为空,我想隐藏它们(例如,如果没有图像,隐藏第一个单元格)。为此,我以这种方式覆盖了 heightForRowAtIndexPath 函数:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch (indexPath.row) {

case 0:
if event?.photo_urls.count == 0{
return 0
}
else{
return 80.0
}
case 1:
if event?.description == ""{
return 0
}
else{
return 90.0
}
default:
return 100.0
}
}

并通过做隐藏单元格

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

switch (indexPath.row) {

case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell", forIndexPath: indexPath) as! UITableViewCell

if event?.photo_urls.count != 0 {
// ...
}
else{
cell.hidden = true
}

return cell

case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("DesCell", forIndexPath: indexPath) as! UITableViewCell
if event?.description != "" {
// ...
}
else{
cell.hidden = true
}

return cell

default:
let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell", forIndexPath: indexPath) as! UITableViewCell
return cell

}
}

到这里没问题,它工作正常!现在,问题是我想根据单元格内容(例如描述高度)使单元格动态化。为此,我使用了

override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 80.0
}

如果我评论 heightForRowAtIndexPath,单元格实际上是动态的,但我不能再隐藏它们了。

对于如何隐藏空单元格并根据其内容应用自动尺寸,您有什么建议吗?

最佳答案

假设您有动态数据并且想在 tableview 中显示它,因此您需要创建一个数据数组来显示。

 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet
var tableView: UITableView
var items: [String] = ["We", "Heart", "nothing" ,"" ,"imageurl", "", "xyz"]

override func viewDidLoad() {
super.viewDidLoad()
reloadTableAfterSorting()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

func reloadTableAfterSorting(){

for var i = 0; i < self.items.count; i++
{

if self.items[i] == ""{
self.items.removeAtIndex(2)

}


}

self.tableView.reloadData()
}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

cell.textLabel?.text = self.items[indexPath.row]

return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}

关于ios - UITableViewCell 的动态维度可以,但是如果为空如何隐藏它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com