UITableViewCell高度不正确,直到通过滚动重新创建单元格

时间:2015-12-19 17:57:39

标签: ios swift uitableview

我已尝试在我修改单元格内容的每个地方设置cell.setNeedsLayout()并调用cell.layoutIfNeeded(),但无论单元格高度不正确,我都会向下滚动/向上滚动。

不正确(初始加载):

正确(滚动后):

的cellForRowAtIndexPath

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("OMCFeedCell", forIndexPath: indexPath) as! OMCFeedTableViewCell
    let p = posts[indexPath.row]

    cell.profileImage.layer.cornerRadius = cell.profileImage.frame.size.width / 2;
    cell.profileImage.layer.masksToBounds = true;
    cell.profileImage.contentMode = .ScaleAspectFit
    cell.profileImage.image = UIImage(named: "profile_blank")

    let API = userAPI()
    API.getByID(p.postEntity) {
        (result: User?) in

        if let u = result {
            cell.profileName.text = u.name

            let uploads = uploadAPI()
            uploads.tryGetImage(u.image) {
                (result: UIImage?) in

                if let i = result {
                    cell.profileImage.image = i
                }
                cell.setNeedsLayout()
                cell.layoutIfNeeded()
            }
        }
    }

    cell.selectionStyle = .None
    let data = p.content!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    let content = try! JSON(NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers))

    if let image = content["image"].string {
        let uploads = uploadAPI()
        uploads.tryGetImage(image) {
            (result: UIImage?) in

            if let i = result {
                let oFrame = cell.postImage.frame
                let width = oFrame.width
                let height = (i.size.height / i.size.width) * width
                cell.postImageHeight.constant = height
                cell.postImageHeight.priority = 999
                cell.postImage.contentMode = .ScaleAspectFit
                cell.postImage.image = i
            } else {
                cell.postImageHeight.priority = 1
                cell.postImage.image = nil
            }
            cell.setNeedsLayout()
            cell.layoutIfNeeded()
        }
    } else {
        cell.postImage.image = nil
        cell.postImageHeight.constant = 0
    }

    cell.postText.text = ""
    if let text = content["text"].string {
        cell.postText.text = text
    }

    cell.postTimestamp.text = JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(p.timestamp).string
    cell.setNeedsLayout()
    cell.layoutIfNeeded()

    return cell
}

1 个答案:

答案 0 :(得分:2)

如果您在显示表格单元格的内容(以及它的高度)后更新,则表格视图不会注意到它。你需要告诉它。

您可以尝试reloadRowsAtIndexPaths:withRowAnimation:,不确定这是否足够。