ios Swift 中的简单 UITableView - 意外发现 nil

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24833391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:27:09  来源:igfitidea点击:

Simple UITableView in Swift - unexpectedly found nil

iosuitableviewswift

提问by soleil

Pretty simple code:

很简单的代码:

func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
    return 1
}

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    return 5
}


func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
    let cell: BookTableViewCell = BookTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "BookCell")
    println("ip: \(indexPath.row)")
    cell.bookLabel.text = "test"

    return cell
}

On the cell.bookLabel.text line I get this:

在 cell.bookLabel.text 行我得到这个:

fatal error: unexpectedly found nil while unwrapping an Optional value

The BookTableViewCell is defined like this:

BookTableViewCell 定义如下:

class BookTableViewCell: UITableViewCell {

    @IBOutlet var bookLabel: UILabel

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

And bookLabel is correctly hooked up in a Prototype cell in the Storyboard. Why am I getting this error?

并且 bookLabel 正确地连接到 Storyboard 的 Prototype 单元格中。为什么我收到这个错误?

采纳答案by Nate Cook

When you create a view in code, its IBOutletproperties don't get hooked up properly. You want the version that you get back from dequeueReusableCellWithIdentifier:

当您在代码中创建视图时,它的IBOutlet属性不会正确连接。您想要从中获得的版本dequeueReusableCellWithIdentifier

let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell

回答by mliu

If you're using storyboard, make sure you don't have this line at the start of your file:

如果您使用的是故事板,请确保您的文件开头没有此行:

self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")

It will overwrite the storyboard and as a result, the outlet links in the storyboard are ignored.

它将覆盖情节提要,因此,情节提要中的出口链接将被忽略。

回答by uplearnedu.com

I was getting this error because I didn't have the identifier written in the Storyboard of the Custom Cell.

我收到此错误是因为我没有在自定义单元的故事板中写入标识符。

StoryBoard

故事板

Also make sure it matches you code in:

还要确保它与您的代码匹配:

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

        let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableCell") as CustomTableCell

        ...
    }

回答by Hieu Vo

Possibly that your view in Main.Storyboard lost its IBOutlet reference in ViewController file, just link it again.

可能是您在 Main.Storyboard 中的视图丢失了 ViewController 文件中的 IBOutlet 引用,只需重新链接即可。

回答by Darius Miliauskas

Do not forget to register nib (tested with Swift3), e. g. inside override func viewDidLoad():

不要忘记注册 nib(用 Swift3 测试),例如在覆盖 func viewDidLoad() 中

self.tableView.register(UINib(nibName: "BookTableViewCell", bundle: nil), forCellReuseIdentifier: "BookCell")

回答by Alex Bailey

The reason why this question gets asked a lot is because it depends on how you setup your tableview and custom CellClass. Do you create your tableview in storyboard or programmatically? Do you create custom .xib Cells and custom Cell classes?

这个问题被问到很多的原因是因为它取决于你如何设置你的 tableview 和自定义 CellClass。您是在故事板中还是以编程方式创建 tableview?您是否创建自定义 .xib 单元格和自定义单元格类?

If you created your tableview programmatically and created custom .xib and Cell class here is the answer for Swift 4:

如果您以编程方式创建 tableview 并创建自定义 .xib 和 Cell 类,这里是Swift 4的答案:

in viewDidLoad:

        customTable.register(UINib(nibName: "NibName", bundle: nil), forCellReuseIdentifier: "NibNameIdentifier")

in cellforRowat:
        let cell = tableView.dequeueReusableCell(withIdentifier: "NibName") as! ClassName

Note:In your cell .xib file make sure you set your identifier in the Attributes inspector ("NibNameIdentifier").

注意:在您的单元格 .xib 文件中,请确保您在属性检查器(“NibNameIdentifier”)中设置了您的标识符。

回答by swiftBoy

You need to check two things

你需要检查两件事

1. Register cell with nib name in viewDidLoad

1.在viewDidLoad中用nib名称注册cell



func viewDidLoad() 
{
    super.viewDidLoad()
    listTableView.register(UINib.init(nibName: "ListProductCell", bundle: nil), forCellReuseIdentifier: "ListProductCell")
 }

2. Create custom cell this way.

2.以这种方式创建自定义单元格。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListProductCell") as! ListProductCell
        return cell
    }

回答by Dani.Rangelov

In my case it was the way the Optional is unwrapped:

就我而言,这是 Optional 的解包方式:

let cellId:String = "ConverterTableCell"
let cell: ConverterTableViewCell = (tableView.dequeueReusableCellWithIdentifier(cellId)! as? ConverterTableViewCell)!

回答by Brigadier

Try doing this:

尝试这样做:

let cell = tableView.dequeueReusableCellWithIdentifier("BookCell", forIndexPath: indexPath) as! BookTableViewCell

and don't forget to set the reuse identifier in your storyboard

并且不要忘记在故事板中设置重用标识符

回答by Dania Delbani

I am getting this error whenever I use reuse Identifername different than the custom class nameunifid those names solve it for me

每当我使用与自定义类名不同的重用标识符名称时,我都会收到此错误 unifid 这些名称为我解决了