【发布时间】: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