ios - 如何在一个 Uitableview 中添加两个 nib UITableViewCell

标签 ios objective-c swift

我是 iOS 开发的新手,可以在一个 tableview 中添加两个不同的 nib 单元格,如果可以,你可以显示任何示例。 提前致谢。

最佳答案

你必须注册2个nibs

tableView.registerNib(UINib(nibName: "Cell1", bundle: nil), forCellReuseIdentifier: "Cell1")
tableView.registerNib(UINib(nibName: "Cell2", bundle: nil), forCellReuseIdentifier: "Cell2")

并在数据源中通过 indexPath 选择它们

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellName = (indexPath.row % 2 == 0) ? "Cell1" : "Cell2"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellName, forIndexPath: indexPath) as UITableViewCell
    return cell
}

enter image description here


what if i wanna to add more then two nib files...

for i in 1...3 {
    let cellID = "Cell" + String(i)
    tableView.registerNib(UINib(nibName: cellID, bundle: nil), forCellReuseIdentifier: cellID)
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellID = (indexPath.row % 3) + 1
    let cellName = "Cell" + String(cellID)
    let cell = tableView.dequeueReusableCellWithIdentifier(cellName, forIndexPath: indexPath) as UITableViewCell
    return cell
}

enter image description here

关于ios - 如何在一个 Uitableview 中添加两个 nib UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29111509/

相关文章:

ios - Cordova 构建 iOS 应用程序': "Could not find module ' npm-registry-client' (Node JS)

objective-c - pi 在 OS X 10.8 上已弃用

ios - UITableView不显示数据

ios - 将用户输入限制为 Swift 中的有效十进制数

ios - UIPickerView Swift 上奇怪的自定义背景颜色

ios - 使用 CALayer 显示 CGPaths 会影响 iOS 的性能吗?

iphone - MPMoviePlayerController 无响应

ios - 播放下一首歌曲时播放器中的flutter audio_manager ios延迟

arrays - 如何从 swift 5 中的正则表达式结果中删除括号?

objective-c - 处理 TableView 单元格中的点击