【问题标题】:Why i cant append my custom object to array?为什么我不能将我的自定义对象附加到数组?
【发布时间】:2020-05-11 19:27:06
【问题描述】:

所以我首先制作了一个自定义对象:

import Foundation
class Website { 
             var name:String
             var pictureLabel:String

    init(title:String,pictureLabel:String) {
        name = title
        pictureLabel = picture
    }
}

然后在我的 tableviewcontroller 类上:

class ViewController:
 UIViewController,UITableViewDelegate,UITableViewDataSource {

    var websites = [Website]()

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 80
        tableView.register(MyCell.self, forCellReuseIdentifier: "MyCell")


        websites.append(Website(title: "facebook.com", pictureLabel: "facelogo"))


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

       func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
        cell.label.text = websites[indexPath.row].name
        return cell }

错误:致命错误:在隐式展开可选值时意外发现 nil:文件

【问题讨论】:

  • 你在哪一行得到错误?
  • 您确定您的 MyCell 设置正确吗?它在 Interface Builder(或 Storyboard)中是否有正确的名称 - “MyCell”?
  • 不幸的是,您在此处包含的错误消息似乎与您包含的代码无关。您是否正确粘贴了错误?您的项目中的其他地方是否有一个名为“file”的变量?
  • @Mohamedab​​oghali,我注意到您找到了答案 here 您可以编辑您的帖子或发布您的答案,以便其他有同样问题的人可以解决它吗?
  • 我看不出您在此处包含的代码将如何编译。在你的WebSite 类中,你有init(title:,picture:),但你用Website(title:pictureLabel:) 调用它。 picturepictureLabel 之间不匹配。请更新您的问题以包含当前编译的代码。

标签: arrays swift uitableview


【解决方案1】:

问题出在那一行

tableView.register(MyCell.self, forCellReuseIdentifier: "MyCell")

应该是

 tableView.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "MyCell")`

【讨论】:

  • 但我仍然不明白为什么它不会在输出窗口上打印数组的内容。我在输出窗口上得到的是 [MyprogectName.List]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
相关资源
最近更新 更多