【发布时间】:2020-10-16 15:34:23
【问题描述】:
我一直在尝试将 tableview 合并到 Xcode 中的 uiview xib 文件中。 我能够显示表格,但无法在其中包含自定义单元格。 这是我的主要代码:
class homemoments:UIView, UITableViewDataSource, UITableViewDelegate {
var posts: Posts!
let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width
@IBOutlet weak var tableView: UITableView!
override init(frame: CGRect) {
super.init(frame: frame)
posts = Posts()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "newsfeedcell")
commitint()
}
//initWithCode to init view from xib or storyboard
required init?(coder: NSCoder) {
super.init(coder: coder)
commitint()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "newsfeedcell") as! NewsfeedTableViewCell
cell.set(post: posts.postsArray[indexPath.row])
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.postsArray.count
}
func commitint(){
let viewFromXib = Bundle.main.loadNibNamed("homemoments", owner: self, options: nil)![0] as! UIView
viewFromXib.frame = self.bounds
addSubview(viewFromXib)
}
}
当我运行此代码时,我的 tableview.register 返回一个错误,指出 tableview 为 nil。 这很奇怪,因为最初我的 tableview.delegation & datasource 也不起作用。所以我通过将 tableview 从 xib 文件拖动到文件所有者来手动添加它们来设置它们。
这是因为我们无法在 xib 中为 tableview 创建自定义单元格吗?因为我确实注意到与 uiviewcontroller 相比,xib 中的 tableview 没有原型模式。
更新
我的表格视图现在显示,但没有显示单元格内容。 我已经搜索并被告知要使用
tableView.register(UINib(nibName: "momentcell", bundle:nil),forCellReuseIdentifier:"momentcell")
见下文:
override init(frame: CGRect) {
super.init(frame: frame)
commitint()
posts = Posts()
tableView.register(UINib(nibName: "momentcell", bundle:nil),forCellReuseIdentifier:"momentcell")
}
//initWithCode to init view from xib or storyboard
required init?(coder: NSCoder) {
super.init(coder: coder)
commitint()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "momentcell") as! momentcell
//cell.set(post: posts.postsArray[indexPath.row])
cell.backgroundColor = .blue
return cell
}
这是我的单元格 xib 文件的屏幕截图
import UIKit
class momentcell: UITableViewCell {
}
现在错误是说
let cell = tableView.dequeueReusableCell(withIdentifier: "momentcell") as! momentcell
这是零
【问题讨论】:
-
cell xib 文件的名称是什么?你只有一个目标吗?您如何创建 homemoments 视图:在故事板、其他 xib 或代码中?
-
无论如何,您都希望您的特定逻辑位于
commoninit中,以便能够从情节提要或代码实例化视图。 -
顺便说一句,您可能想查看一些 swift 样式指南,通常认为所有类型都应以大写字母开头并使用驼峰式大小写(
MomentCell,HomeMoments)。这是许多开发人员的普遍承诺。
标签: ios swift uitableview uiview xib