【发布时间】:2016-04-20 00:13:57
【问题描述】:
我正在使用 Swift 2 构建一个 iOS 应用程序,该应用程序使用自定义表格视图单元格、附加标签、图像视图等(我们将类称为 CustomTableViewCell)。我已经为每个子视图建立了类故事板连接,并为单元格分配了一个标识符。我已经模拟了数据并尝试运行应用程序以检查单元格是否正确映射,并且看起来没问题。
问题是我不能将出队的单元格视为CustomTableViewCell 来测试其属性的值。当我向下转换从tableView(tableView, cellForRowAtIndexPath: indexPath) 返回的单元格时,所有自定义属性值都变成nil,我的测试失败了。
这是我的代码:
MyViewControllerTests.swift
func testShouldConfigureTableViewCellToDisplayNotification() {
// Given
sut.tableView = TableViewSpy()
let items = [ <some items to display> ]
sut.displayedItems = items
// When
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = viewController.tableView(viewController.tableView, cellForRowAtIndexPath: indexPath) as! CustomTableViewCell
// Then
XCTAssertEqual(cell.detailLabel?.text, "foo", "A properly configured table view cell should display the notification detail")
XCTAssertEqual(cell.titleLabel?.text, "Bar", "A properly configured table view cell should display the notification title")
XCTAssertEqual(cell.dateLabel?.text, "15/04/2016", "A properly configured table view cell should display the notification date")
}
MyViewController.swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CustomTableViewCell"
let displayedItem = displayedItems[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomTableViewCell
if cell == nil {
cell = CustomTableViewCell(style: .Value1, reuseIdentifier: cellIdentifier)
}
cell!.dateLabel?.text = displayedItem.date
cell!.detailLabel?.text = displayedItem.detail
cell!.titleLabel?.text = displayedItem.title
return cell!
}
CustomTableViewCell.swift
class CustomTableViewCell: UITableViewCell {
// MARK: Properties
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
@IBOutlet weak var titleLabel: 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
}
}
【问题讨论】:
标签: ios swift uitableview