OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 UIView 中嵌入 UITableView? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:41
标题: ios - 如何在 UIView 中嵌入 UITableView?

我在使用 xib 构建的自定义 View 中有一个 UIView。我需要在所述 View 中显示一个 UITableView 。起初我考虑放置一个 container 并在其中嵌入一个 UITableViewController。原来我不能将 containers 放在 xib 文件中,或者至少没有办法从 IB 中做到这一点,因为它没有出现在右下角的 View 部分中。

我可以通过编程方式创建一个 UITableView 并将其添加为 View 的 subview 。它按预期显示,但我似乎无法在其中添加单元格。我还尝试创建一个行为良好的 UITableViewControllerstoryboard View 关联,按如下方式实例化该 Controller :

let storyboard = (UIStoryboard(name: "Main", bundle: nil)) 让 vc = storyboard.instantiateViewControllerWithIdentifier("tableViewController") 为! TestTableViewController

然后尝试访问 UITableView 的 socket ,它是 nil。然后我在某处读到我应该做一个 vc.loadView() 因为顾名思义,它会加载 View 并且我的 IBOutlet 不会是 nil。这行得通。 socket 的 nil 更长。但是,当我将容器 View 中的表格添加为 subview 时,它仍然不显示任何单元格。只有分隔线,没有内容。我已经没有想法了!

编辑

我没有任何 UITableViewCell 实现,因为表是静态的。



Best Answer-推荐答案


好的方法是在自定义 View 中使用 UITableview:

如果您以编程方式添加 tableview,则使用 Nib 或 UITableview 子类注册您的单元格,如

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

如果你使用 Xib 创建 UITableviewCell。

tableView.registerClass(UITableViewCellSubclass.self, forCellReuseIdentifier: "UITableViewCellSubclass") // using code.
tableView.delegate = self
tableView.dataSource = self

然后使用 2 个必需的委托(delegate)。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2 
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("UITableViewCellSubclass", forIndexPath: indexPath) as! UITableViewCellSubclass
}

希望我回答了你的问题。

关于ios - 如何在 UIView 中嵌入 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41781505/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4