【问题标题】:iOS Swift - Custom UITableViewCelliOS Swift - 自定义 UITableViewCell
【发布时间】:2014-06-19 03:35:54
【问题描述】:

我确信问题本身已经被正确地提出并回答了,但是在 Objective C 中。我正在使用 swift 并且想知道如何正确地自定义 UITableViewCell。我在http://www.appcoda.com/customize-table-view-cells-for-uitableview/ 处遵循了本教程,但我坚持正确初始化和使用我创建的自定义类和 XIB 文件。是的,我是菜鸟。这是我没有自定义的标准单元:

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

    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myCell")
    cell.text = postMgr.posts[indexPath.section].title
    cell.detailTextLabel.text = postMgr.posts[indexPath.section].description
    return cell

}

如果有人可以将教程中的 Obj C 翻译成 swift,那就太好了。这里是:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"SimpleTableCell";

SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) 
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
} 

cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];

return cell;

}

不确定这是否适用于 iOS7/8。如果有人有更好更简单的自定义单元格的方法,请用 Swift 语言告诉我。

我已经感谢您的帮助。我是初学者,请多多包涵:)

公里

【问题讨论】:

  • 我相信UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myCell") 可以返回 nil。您需要检查这种情况,如果是,则使用常规构造函数创建它。您得到的具体错误是什么?

标签: ios objective-c xcode uitableview swift


【解决方案1】:

我刚刚将教程示例应用程序移植到Swift。我仍在使用用 Objective-C 编写的相同 CustomTableViewCell(使用桥接头来利用该类)。我的cellForRowIndexPath 看起来像

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

    var  cell:SimpleTableCell! = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? SimpleTableCell

    if (cell == nil)
    {
        let nib:Array = NSBundle.mainBundle().loadNibNamed("SimpleTableCell", owner: self, options: nil)
        cell = nib[0] as? SimpleTableCell
    }

    cell.nameLabel.text = tableData[indexPath.row]
    cell.thumbnailImageView.image = UIImage(named:thumbnails[indexPath.row])
    cell.prepTimeLabel.text = prepTime[indexPath.row];

    return cell;
}

在这里找到完整的源代码:TableViewApp-Swift

【讨论】:

  • 非常感谢..像魅力一样工作:D(不知道为什么它是-1)
猜你喜欢
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多