【发布时间】:2016-04-01 00:23:26
【问题描述】:
我相信创建自定义类来配置表格单元格是 iOS 开发的标准做法。我也将这种做法应用于我的应用程序,但我遇到了一些问题。
我有两个表格视图 - 每个 ViewController 一个 - 它们的单元格使用相同的自定义单元格类。
CustomCellClass
import UIKit
class RecipeCategoryCell: UITableViewCell {
@IBOutlet weak var recipeCategoryLabel: UILabel!
@IBOutlet weak var chooseCategoryLabel: UILabel!
//...
func configureCell(recipe: Recipe) {
let category = recipe.category as? RecipeCategory
recipeCategoryLabel.text = category!.name
}
func configureNewCell(category: RecipeCategory) {
recipeCategoryLabel.text = category.name
}
// re-configure receiver's viewcontroller cell with selected category value
func configureSelectedCategoryCell(selectedCategory: String) {
recipeCategoryLabel.text = selectedCategory
}
// configure all available category names in the sender's viewcontroller
func configureChooseCategoryCell(category: RecipeCategory) {
chooseCategoryLabel.text = category.name
}
}
@IBOutlet weak var recipeCategoryLabel: UILabel! 属于接收者 viewController,@IBOutlet weak var chooseCategoryLabel: UILabel! 属于发送者 viewController
我在recipeCategoryLabel.text = selectedCategory 这一行的第三个函数有一个问题,Xcode 说
致命错误:在展开 Optional 时意外发现 nil 价值
我在使用相同 IBOutlet recipeCategoryLabel 的其他函数上没有这个问题,但只有函数 configureSelectedCategoryCell() 使用选定的类别值重新配置接收器 ViewController 单元格。
所以我可以肯定地说,这不是故事板的连接问题。
我想这是因为在多个地方使用了相同的 IBOutlet 属性。但问题是,我必须使用相同的属性,这样我才能设置默认值、更新选定的值、在同一个标签上设置以前持久的值。
我不知道我的解释是否足够清楚,但基本上我无法将接收者ViewController 的表格单元格标签设置为从发送者ViewController 传递的选定类别值。
更新
而configureSelectedCategoryCell()在接收者的ViewController扩展中被调用:
extension CreateRecipeVC: RecipeCategoryTableVCDelegate {
func categoryController(controller: RecipeCategoryTableVC, didSelectCategory category: String) {
selectedCategory = category
self.navigationController?.popViewControllerAnimated(true)
let cell = RecipeCategoryCell()
cell.configureSelectedCategoryCell(selectedCategory)
}
}
【问题讨论】:
-
你确定你 selectedCategory 不是一个 nil 对象吗?
-
您是否可能在组件加载并连接到 IBOutlet 之前调用此函数?
-
您何时调用
configureSelectedCategoryCell以及使用哪些机制(NSNotification、直接调用等)? -
请查看更新图片。它使用正确的字符串打印 selectedCategory,在控制台中显示“Drink”。
-
这看起来很可疑:let cell = RecipeCategoryCell()。为什么不调用 dequeueReusableCellWithIdentifier?见developer.apple.com/library/ios/documentation/UIKit/Reference/…
标签: ios xcode swift uitableview