我正在学习本教程:
http://www.xmcgraw.com/learn-how-to-create-an-ios-app-using-homekit/
文章中有指向包含代码的 GitHub 的链接。
我正在尝试启动并运行一个简单的 HomeKit 应用程序来打开和关闭灯。我已经通读了 Apple 的 HomeKit 入门指南。我确实拥有付费的 Apple 开发者成员(member)资格,配置文件允许我构建应用程序并在我的 iPhone(6s 和 iOS 10.2)上运行它。我正在使用 Xcode 8.2.1 并且 HomeKit Accessory Simulator 正在运行,我可以看到我创建的模拟灯,因为我可以将它们打印到控制台,它们都按名称显示。
问题是,我无法将它们添加到 accessories 数组中,也无法将它们作为单元格添加到 TableView 中。我检查并重新检查了单元格上的重用标识符“accessoryId”是否与我在代码中使用的相匹配。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "accessoryId") as UITableViewCell? {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "accessoryId")
let accessory = accessories[indexPath.row] as HMAccessory
cell.textLabel?.text = accessory.name
return cell
}
return UITableViewCell()
}
我已经查看了许多关于 SO 的关于相同错误的其他问题,但似乎没有任何修复有帮助。
当 accessories.append(accessory) 被注释掉时,打印函数将控制台正确记录从模拟器中找到的所有附件的名称。
func accessoryBrowser(_ browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory) {
print(accessory.name)
accessories.append(accessory)
tableView.reloadData()
}
但是当我取消注释 accessories.append(accessory) 时,我得到这个错误
UITableView... failed to obtain a cell from its datasource"
我该如何解决?
最佳答案
这一行对我来说没有意义:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "accessoryId")
您正在 cellForRowAtIndexPath 内以及每次调用时为表注册单元格。尝试将其放在 viewDidLoad 中。但我认为,如果您使用 Storyboard,则根本不需要这样做。
这是 Swift 3 中的语法(您的问题标题说您正在使用它):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "accessoryId") {
// OR for Custom Cell:
// if let cell = tableView.dequeueReusableCell(withIdentifier: "accessoryId") as? CustomTableViewCell {
return cell
}
return UITableViewCell()
}
关于ios - 从教程制作简单的 HomeKit 应用程序并在附加 HMAccessory 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893908/