在tableView单元格中显示类的数组

问题描述 投票:-8回答:3

我声明了一个包含所有变量的类。

class Xyz
{
  var a: String?
  var b: String?
}

在其他viewController中,我声明了该类的数组。

 var arr = [Xyz]()
 var arr2 = ["title1","title2"]

在Json Parsing之后,我在这个数组中附加值。

var temp = Xyz()
var dict = item as! NSDictionary
temp.a = (dict.value(forKey: "a") as? String) ?? ""
temp.b = (dict.value(forKey: "b") as? String) ?? ""
self.arr.append(temp)

我应该如何在一个单元格中显示这个数组?

cell.textLabel?.text = arr2[indexPath.row]
//The above array shows the title of the row
cell.detailTextLabel?.text = String(describing: arr[indexPath.row])
//indexPath doesn't work here (error: indexPath out of range)
//The reason is the 'arr' array has class in it

上面的语句给出了错误,因为数组中包含类,而不是值。

 cell.detailTextLabel?.text = String(describing: arr[0].a)
 cell.detailTextLabel?.text = String(describing: arr[0].b)

是我可以访问我的价值观的唯一方法。由于我无法在我的tableView中显示此数组。

如何在tableView单元格上显示数组的内容(每个单独的单元格上)?

ios arrays swift class
3个回答
3
投票

代码中存在许多错误/错误的编程习惯。

首先将该类命名为以大写字母开头,并将属性声明为非可选属性,因为它们将包含非可选值。 (将可选项声明为不在不写入初始化程序的不在场的做法是不良习惯之一。)

arr2中行的标题包含在类中的title属性中,以避免任何超出范围的异常。

class Xyz
{
    var a : String
    var b : String
    var title : String

    init(a: String, b: String, title: String) {
        self.a = a
        self.b = b
        self.title = title
    }
}

声明数据源数组

var arr = [Xyz]() // `var arr: [xyz]()` does not compile

填充数据源数组

let dict = item as! [String:Any] // Swift Dictionary !!
let temp = Xyz(a: dict["a"] as? String) ?? "", b: dict["b"] as? String) ?? "", title: "title1")
self.arr.append(temp) // `self.arr.append(value)` does not compile

cellForRow中从数组中获取Xyz实例并使用属性

let item = arr[indexPath.row]
cell.textLabel?.text = item.title

cell.detailTextLabel?.text = item.a + " " + item.b

因为无论如何所有属性都是字符串,所有String(describing初始化器(从String创建String)都是荒谬的。


0
投票

您似乎想要显示您的类属性

更换线

cell.detailTextLabel?.text = String(describing: arr[indexPath.row])

cell.detailTextLabel?.text = "\(arr[indexPath.row].a) \(arr[indexPath.row].b)"

0
投票

我经历了以下所有答案。但他们都没有产生解决方案。所有解决方案中的问题是array打印在同一个单元格上,而另一个单元格为空(包括Vadian提供的答案 - 它会给出错误,因为它会在同一行中打印所有值)。在单元格上打印array时,你必须循环,但没有一个答案提供。这将给Index out of range带来错误。我遇到的最佳解决方案是使用switchenum。由于switchenum你可以为每一行设置一个条件,并根据你可以从array打印项目。在这里,我把简单的array项目“标题”作为case,并根据印刷的类array

解决方案: - 以下代码帮助我实现了我的要求。

注意: - enumswitch更受欢迎。我使用switch因为易于理解并完成了我的工作。

let a = arr2[indexPath.row]
let item = arr[0]

switch a
{
case "title1":
   cell.detailTextLabel?.text = item.a
   return cell
case "title2" :
   cell.detailTextLabel?.text = item.b
   return cell
default:
   break
}
© www.soinside.com 2019 - 2024. All rights reserved.