我正在为我的 tableView
创建自定义单元格。我制作了一个 swift 文件:
import Foundation
import UIKit
class CellForPost: UITableViewCell {
@IBOutlet weak var postLikes: UILabel!
@IBOutlet weak var postText: UILabel!
@IBOutlet weak var postDate: UILabel!
@IBOutlet weak var postPhoto: UIImageView!
}
并在委托(delegate)方法中实现:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CellForPost
cell.postPhoto.image = UIImage.init(data: (posts[indexPath.item].postPhoto)! as NSData)
cell.postText.text = posts[indexPath.item].postText
cell.postLikes.text = String(posts[indexPath.item].postLikes!)
cell.postDate.text = timestampToDate(posts[indexPath.item].postDate!)
return cell
}
当帖子内容完整时,一切都很好,但是当例如没有照片(在 post
结构中是可选的)时,它会崩溃并显示消息
fatal error: unexpectedly found nil while unwrapping an Optional value
我理解这个消息,所以我尝试制作
@IBOutlet weak var postPhoto: UIImageView?
就像一个可选值,但它不起作用,因为编译器要我在插入到单元格之前展开值。
附言如果可以给出一个关于在 imageView
为 nil 时完全删除并调整行高以适合其大小的简短建议。
最佳答案
你不需要修改你的 outlets 声明,你需要在 cellForRowAtIndexPath
方法中检查 nil(并设置 nil 作为值)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CellForPost
var image: UIImage? = nil
if let imageData = posts[indexPath.item].postPhoto {
image = UIImage.init(data: imageData)
}
cell.postPhoto.image = image
cell.postText.text = posts[indexPath.item].postText
var postLikes: String? = nil
if let likesData = posts[indexPath.item].postLikes {
postLikes = String(likesData)
}
cell.postLikes.text = postLikes
var postDate: String? = nil
if let dateData = posts[indexPath.item].postDate {
postDate = timestampToDate(dateData)
}
cell.postDate.text = postDate
return cell
}
关于swift - 带有选项的自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38223877/