菜鸟教程小白 发表于 2022-12-12 11:41:49

ios - 如何在 UIView 中嵌入 UITableView?


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

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

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

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

<p><strong>编辑</strong></p>

<p>我没有任何 <code>UITableViewCell</code> 实现,因为表是静态的。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>好的方法是在自定义 View 中使用 UITableview:</p>

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

<pre><code>tableView.registerNib(UINib(nibName: &#34;UITableViewCellSubclass&#34;, bundle: nil), forCellReuseIdentifier: &#34;UITableViewCellSubclass&#34;)
</code></pre>

<p>如果你使用 Xib 创建 UITableviewCell。</p>

<pre><code>tableView.registerClass(UITableViewCellSubclass.self, forCellReuseIdentifier: &#34;UITableViewCellSubclass&#34;) // using code.
tableView.delegate = self
tableView.dataSource = self
</code></pre>

<p>然后使用 2 个必需的委托(delegate)。</p>

<pre><code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
return 2
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(&#34;UITableViewCellSubclass&#34;, forIndexPath: indexPath) as! UITableViewCellSubclass
}
</code></pre>

<p>希望我回答了你的问题。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 UIView 中嵌入 UITableView?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41781505/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41781505/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 UIView 中嵌入 UITableView?