我正在尝试设置一个包含 2 个单元格的表格 View 。两个单元都有自己的类,并且有自己的配置方法。在代码中,当我到达 cellforrowatindexpath 方法时,我陷入困境。我只能将其中一个单元出队并调用它的方法,这意味着另一个单元将不会配置。我想同时配置两者。这是我(当前)在 cellforrow 方法中尝试的内容:
let cells = [tableView.viewWithTag(1), tableView.viewWithTag(2)]
for view in cells {
var reuseIdentifier = "cellID"
switch view?.tag {
case 1: // error occurs here
reuseIdentifier = "storyCell"
let storyCell1 = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StoryCell1
storyCell1.theCategory.text = newsItem.storyCategory
storyCell1.theTitile.text = newsItem.titleText
storyCell1.firstParagraph.text = newsItem.paragraph1
case 2: // error occurs here too
reuseIdentifier = "storyCell2"
let storyCell2 = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StoryCell2
storyCell2.configureCell(newsItem)
default:
}
在 Storyboard 中,我分别为这两个单元格指定了 1 和 2 标签,因此数组位于最开始的位置。我对这种方法有两个问题。
我无法使用它,因为 switch 语句引发错误:“Int”类型的表达式模式无法匹配“Int”类型的值?
即使没有出现上述错误,我仍然只能在方法结束时返回一个单元格。
任何对我的方法的帮助或不同的、更好的方法来处理这个问题将不胜感激。谢谢!
编辑:
因为我确定我已经添加了 tag 属性,所以我强制解开 view!.tag 属性,错误就消失了。所以,现在剩下第二个问题。
最佳答案
我不太明白你想在这里做什么。
我认为您想要做的是在 tableView(_:cellForRowAtIndexPath:)
方法中配置并返回两个单元格。如果你真的想这样做,那你就完全错了。
TableView 的数据源方法提出问题。您的工作就是通过返回一个值来回答这些问题。例如,numberOfSectionsInTableView(_:)
询问您应该有多少个部分。示例答案可能是 return 1
、return 10
等。
类似地,tableView(_:cellForRowAtIndexPath:)
会询问
What should be the cell that should be shown in the section and row specified by the index path?
然后您通过返回 UITableViewCell
来回答。您无法返回两个单元格,因为它要求您提供一个要在特定部分和行中显示的单元格。如果你给它两个单元格来显示, TableView 如何显示它们?这没有道理! TableView 中的每一行只能显示一个单元格!
因此,不要为单元格提供标签,而是使用 indexPath
参数来决定要创建哪个单元格。
假设您希望第一行显示标识符为“storyCell”的单元格。您希望第二行显示标识符为“storyCell2”的单元格。并且您的表格 View 只有一个部分。你可以这样做:
switch indexPath.row {
case 0:
reuseIdentifier = "storyCell"
let storyCell1 = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StoryCell1
storyCell1.theCategory.text = newsItem.storyCategory
storyCell1.theTitile.text = newsItem.titleText
storyCell1.firstParagraph.text = newsItem.paragraph1
return storyCell1
case 1:
reuseIdentifier = "storyCell2"
let storyCell2 = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StoryCell2
storyCell2.configureCell(newsItem)
return storyCell2
default:
// this shouldn't be reached if you do your other data source methods correctly
return UITabeViewCell()
}
你应该删除这些废话:
let cells = [tableView.viewWithTag(1), tableView.viewWithTag(2)]
for view in cells {
var reuseIdentifier = "cellID"
关于ios - View 标签属性的 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38758226/