在Swift中以编程方式创建UITableViewCell [英] Creating a UITableViewCell programmatically in Swift

查看:88
本文介绍了在Swift中以编程方式创建UITableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的 UITableView 创建自定义单元格,但我遇到了一些困难。

I am trying to create a custom cell for my UITableView but I am having some difficulty.

首先我无法使用Interface Builder,因为我遇到了 Xcode中此错误的变体。每次我在Interface Builder中单击一个元素时,该视图中的所有内容都会获得零高度和宽度,并在视图外部重新定位。此外,我想学习如何以编程方式执行此操作。

First off I cannot use the Interface Builder, as I am experiencing a variation on this bug in Xcode. Every time I click on an element in the Interface Builder everything in that view gets a height and width of zero and gets repositioned outside of the view. Besides, I would like to learn how to do this programmatically.

其次,我正在为我的项目使用Swift语言。 我一直在努力遵循此演示,尽我所能将Objective C代码转换为Swift,但每当遇到问题时,我最终都会陷入困境。我认为这是因为我没有正确转换代码。

Secondly I am using the Swift language for my project. I have been trying to follow this demonstration, and doing my best to convert the Objective C code over to Swift, but whenever I run into problems I end up being stuck. I presume this is because I am not converting the code over correctly.

第三,我发现了这个视频但是尽管相当难以理解(许多代码只是被复制和粘贴而没有太多解释它的作用或原因),它仍然最终使用了Interface Builder来更改各个部分。

Thirdly I found this video but despite being fairly difficult to follow (lots of the code is just copied and pasted without much explanation to what it does or why), it still ends up using the Interface Builder to change various parts.

我有一个基本的 UITableView 设置正常。我只是希望能够在该表视图中添加一个自定义单元格。

I have a basic UITableView set up fine. I just want to be able to add a custom cell to that table view.


  • 这可以使用纯编程完成,或者我是否需要使用界面生成器?

  • Can this be done using pure programming, or do I need to use the Interface Builder?

任何人都能指出我正确的方向或帮助我在Swift中以编程方式创建自定义单元吗?

Can anyone point me in the right direction or help me out in creating a custom cell programmatically in Swift?

非常感谢。

推荐答案

一般情况下:在纯编程中一切皆有可能; - )

In general: Everything is possible in pure programming ;-)


  1. 为tableView单元格创建一个自定义类设置所有元素,属性和可视布局。实现所需的方法 init(style,reuseidentifier)

在<$ c的自定义类中$ c> UITableViewController 使用 registerClass(forCellReuseIdentifier)注册自定义单元格类

为自定义tableViewController设置委托和数据源

Setup your delegate and datasource for the custom tableViewController

最后,在 cellForRowAtIndexPath :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myReuseIdentifier", forIndexPath: indexPath) as MyCustomTableViewCell 

    // configure the cell using its properties

    return cell
}

这应该是基本步骤。

这篇关于在Swift中以编程方式创建UITableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆