在tableViewCell中设置字符串数组

时间:2018-11-11 17:45:07

标签: ios swift uitableview

我有一个tableViewCell,我需要将一个数组传递给tableViewCell,而不仅仅是传递给文本标签或类似的东西。我让我的代码显示出来。

我的TableViewController:

let subjectsDict = ["Spanish": ["Lesson 1", "Lesson 2"], "Math":["Problem set 1", "Problem set 2"], "Science": ["Lab"]]

let subjectArray = ["Spanish", "Math", "Science"]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "subjectCell", for: indexPath) as? SubjectTableViewCell else {
        return UITableViewCell()
    }

    cell.subjectList = subjectsDict[subjectArray[indexPath.row]]

    return cell
}

我的tableViewCell看起来像这样。

class subjectTableViewCell: UITableViewCell {
        var subjectList: [String] = []

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style , reuseIdentifier: reuseIdentifier)
        setUpTable()
    }
    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        setUpTable()
    }
    func setUpTable() {
        print(subjectList)
    }
        //other code for creating the cell
}

但是当我从subjectTableViewCell打印subjectList时,它会打印none

3 个答案:

答案 0 :(得分:1)

您的代码不会尝试使用值subjectList更新单元格的内容。您显示的只是一个print

还请注意,在尝试设置print之前,您的subjectList已被调用。并记住,细胞会被重用。 setUpTable只会被调用一次,但是subjectList会随着使用该单元格而不断被设置。

最简单的解决方案是在设置subjectList后更新单元格。

var subjectList: [String] = [] {
    didSet {
        textLabel?.text = subjectList.joined(separator: ", ")
    }
}

我假设您正在使用标准的textLabel属性。如果您有自己的标签,请相应更新。

答案 1 :(得分:0)

如果您只想在单元格中的setUpTable()更新时调用subjectList,请尝试使用:

var subjectList: [String] = [] {
    didSet {
        setUpTable()
    }
}

答案 2 :(得分:0)

您正在初始化表视图单元时尝试打印subjectList,因此此时您尚未设置subjectList。如果要打印subjectList,可以在设置它之后进行。

执行此行之后:

cell.subjectList = subjectsDict[subjectArray[indexPath.row]]
相关问题