我从解析中获取数据并将它们放入表视图中(想想帖子)。在我的应用中,有用户分享的帖子;其中一些有图像,有些没有。我想制作两个不同的视图单元格,例如其中一个具有图像视图而另一个没有。
但是,我在设置数据时遇到了麻烦。如果在解析过程中帖子中没有Image,我会得到一个nil异常。如何解决这个问题并将它们放在不同的视图中?
这是我从解析中获取数据的地方:
if let objects = objects {
for object in objects {
let titles = object["titleOfPost"] as! String
self.postTitles.append(titles)
let messages = object["messageOfPost"] as! String
self.postMessages.append(messages)
if (object["imageOfPost"] != nil) {
let feedImageFile:PFFile = object["imageOfPost"] as! PFFile
feedImageFile.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if (imageData != nil) {
self.postImages.append(UIImage(data:imageData!)!)
}
})
}
}
}
这是我在表格视图中使用的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TextViewCell", forIndexPath: indexPath) as! TextPostTableViewCell
cell.titleOfPost.text = postTitles[postTitles.count - indexPath.row-1]
cell.messageOfPost.text = postMessages[postMessages.count - indexPath.row-1]
cell.username.text = "osman"
cell.profileImage.image = UIImage(named:"icon_ios_user")
cell.email.text = "email@email.com"
return cell
}
如何解决数据问题,然后在一个表格视图中放置2个不同的视图单元格,按共享帖子的时间排序?
答案 0 :(得分:0)
您可以使用if语句检查图像是否存在,例如:
if let image = dictData.objectForKey("Image"){
cell.imageView?.image = image as? UIImage
}
如果您需要在表格中显示2个完全不同的单元格,则创建自定义单元格,为其提供唯一的重用标识符并在viewDidLoad中注册:
override func viewDidLoad() {
super.viewDidLoad()
// Custom Cell with Image
self.tableView.registerNib(UINib(nibName: "CustomCellImage", bundle: nil), forCellReuseIdentifier: "CustomCellImage")
// Custom Cell with Text
self.tableView.registerNib(UINib(nibName: "CustomCellText", bundle: nil), forCellReuseIdentifier: "CellText")
}
然后在cellForRowAtIndexPath中选择要在任何条件下使用的单元格:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dictData : NSDictionary = arrayOfData.objectAtIndex(indexPath.row) as! NSDictionary
let strTypeObject = dictData.objectForKey("ObjectType") as! String
if strTypeObject == "ImageType"
{
let cell: CustomCellImage = tableView.dequeueReusableCellWithIdentifier("CustomCellImage", forIndexPath: indexPath) as! CustomCellImage
cell.lblImageText.text = dictData.objectForKey("ObjectMessage") as? String
cell.customImageView.image = dictData.objectForKey("Image") as? UIImage
return cell
}
if strTypeObject == "StringType"
{
let cell: CustomCellText = tableView.dequeueReusableCellWithIdentifier("CellText", forIndexPath: indexPath) as! CustomCellText
cell.lblJustSomeText.text = dictData.objectForKey("ObjectMessage") as? String
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = dictData.objectForKey("ObjectMessage") as? String
if let image = dictData.objectForKey("Image"){
cell.imageView?.image = image as? UIImage
}
return cell
}