【问题标题】:Access to Custom UITableViewCell UILabel Text in Swift throws error在 Swift 中访问自定义 UITableViewCell UILabel 文本会引发错误
【发布时间】:2014-06-24 15:57:40
【问题描述】:

我正在尝试创建一个自定义 UITableViewCell,其中包括我自己的 UILabel。

我使用 Swift 创建了一个单视图应用程序,并添加了一个带有 .xib 文件的 Cocoa Touch 类,然后我添加了 UILabel 并在新文件中创建了一个 Outlet(CustomCell 类)。

在主 StoryBoard 中,我添加了一个 UITableView,并用数据初始化它(实现 UITableViewDataSource 和 UITableViewDelegate)。

当我尝试访问 UILabel 中的文本属性时,它会失败并出现以下错误:

致命错误:无法打开 Optional.None

这是我的 CustomCell 类:

import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet var myLbl: UILabel

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func SetValue(value: String){
        myLbl.text = value  // Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

更新: 这是在主 ViewController 中创建单元格的代码:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
        var cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Default")
        cell.SetValue(stringArray[indexPath.row])
        return cell;
    }

【问题讨论】:

    标签: ios xcode uitableview swift


    【解决方案1】:

    您收到该错误是因为 myLbl 为 nil。

    那是因为您没有使用 Nib 创建单元格。您正在使用带有样式的 init。您应该做的是将 nib 注册到 table view 上,然后在 tableview 上使用 deque:

    override func viewDidLoad() {
        var cellNib = UINib(nibName:"ANibName", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "default")
    }
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
        var cell = tableView.dequeueReusableCellWithIdentifier("default", forIndexPath: indexPath) as CutomCell
        cell.SetValue(stringArray[indexPath.row])
        return cell;
    }
    

    但是,如果您要在视图控制器的 Nib 中创建模板单元格,则不必为该单元格注册单独的 Nib,但您仍需要像上面那样对单元格进行 deque。

    【讨论】:

    • 它看起来像他附加了 OK,我看到 IBOutlet 行旁边的编辑器左侧的圆圈。 (圆圈是灰色的)
    • 那你确定你真的是从笔尖加载它吗?你是如何创建单元格的?
    • 问题已更新。但我很确定这不是问题。如果我以相同的方式创建单元格但没有 UILabel.text,它的工作正常。
    • @user3210784 好的,我更新了我的答案。您不是从笔尖加载单元格,而是以编程方式创建它
    • 它工作正常,但现在我有其他错误:'Could not load NIB in bundle:'NSBundle /admin/Library/Developer/CoreSimulator/Devices/11675D3B-7030-4DC5-8D7A- 2D2693DAE3EE/data/Containers/Bundle/Application/D08FDC90-6F4F-4D21-95FA-0C5DBCF5B0E8/TableViewCellsTest.app>(已加载)',名称为'ANibName''
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多