调整UICollectionViewCell的大小

时间:2017-08-09 07:45:29

标签: ios swift3 uicollectionview uicollectionviewcell

我正在使用UICollectionView来显示记录,对于我创建了一个xib文件的记录,如下所示

enter image description here

1。标题webview包含帖子标题(如果有) 2。 Imageview包含帖子图片(如果有) 3.文本webview包含帖子文本(如果有)

数据来自远程服务器。 我创建了一个单独的UIcollectionViewCell类来设置数据。

我想根据单元格数据调整UIcollectionViewCell的大小。以前我是Overriding

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

return size
}

完成它,但对我来说并不完美。我如何根据

的大小调整单元格的大小

1。标题html

2。图像

3。文字html

现在我要做的是

在我的UIcollectionViewCell类

    if text != nil {
    postTextWebView.delegate = self            
postTextWebView.loadHTMLString(text!, baseURL: bundleURL as URL)
            }
            else{
                postTextWebView.loadHTMLString("", baseURL: nil)
                postTextHeightConstraint.constant = 0
            }

这个课程重写 UIWebViewDelegate的webViewDidFinishLoad()函数

 func webViewDidFinishLoad(_ webView: UIWebView) {
       var frame : CGRect = webView.frame;
        frame.size.height = 1;
        webView.frame = frame;
        let fittingSize : CGSize = webView.sizeThatFits(.zero)
        frame.size = fittingSize;
        webView.frame = frame;


        if let sizeCalculator = self.dynamicSizeCalculator {
            sizeCalculator.calculateVariableSize(tag: postTextWebView.tag, variableSize: fittingSize.height, indexPath: IndexPath.init(row: postTextWebView.tag, section: 0))
        }
    }

protocol DynamicSizeCalculator:class{
    func calculateVariableSize(tag:Int,variableSize:CGFloat,indexPath:IndexPath)
}

在我的View控制器类

var variableHeights:[CGFloat]? = []
    var isFirstTimeLoaded : Bool = false

从服务器获取数据时Bool值变为true

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        self.collectionView.collectionViewLayout.invalidateLayout()
        super.viewWillTransition(to: size, with: coordinator)
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell:Cell
      cell = collectionView.dequeueReusableCell(withReuseIdentifier: "softBoardPostCell", for: indexPath) as! Cell
                cell.postTextWebView.tag = indexPath.row
                    cell.dynamicSizeCalculator = self
                    cell.drawCell(posts[indexPath.row])
                    cell.sbActionChosenListner=self
                    return cell

            }


            func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

                return posts.count
            }


 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        var cellHeight:CGFloat = 20 + 19.5 + 9.5+14.5+8+16+9+16+10+34+12+14.5+8.5+32+20+12;
        if isFirstTimeLoaded{
            variableHeights?.insert(0.0, at: indexPath.item)
        }
        var cellHeight : CGFloat = 20+48+11+14+10+14.5+14.5+11.5+32+13
        if let userName = posts[indexPath.item].user_name{
            let userNameRect = NSString(string:userName).boundingRect(with: CGSize(width:view.frame.width,height:200), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 16)], context: nil)
            cellHeight = cellHeight + userNameRect.height
        }
        if let postTitle = posts[indexPath.item].post_text_title?.html2String{
             let titleRect = NSString(string:postTitle).boundingRect(with: CGSize(width:view.frame.width,height:1000), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 16)], context: nil)
            cellHeight = cellHeight+titleRect.height 
        }


        if  posts[indexPath.item].post_text != nil{
cellHeight = cellHeight+(variableHeights?[indexPath.row])!

        }


        if  posts[indexPath.item].post_img_url != nil{


            let contentType = posts[indexPath.item].post_content_type!
            switch contentType {
            case "EXTERNAL_LINK":

                fallthrough
                case "EXTERNAL_VIDEO":
                cellHeight = cellHeight+300
                break
            default:
                let postImageUrl=posts[indexPath.item].post_img_url!
                let imageUrl = URL(string: postImageUrl)

                do{
                    let imageData = try Data(contentsOf: imageUrl!)
                    let image = UIImage(data: imageData)
                    if image != nil{
                        cellHeight = cellHeight + image!.size.height
                    }
                }
                catch let error {
                    print("ERROR : \(error.localizedDescription)")
                }
            }



            }


        return CGSize(width:view.frame.width,height:cellHeight)
    }



 func calculateVariableSize(tag:Int,variableSize:CGFloat,indexPath:IndexPath){
        isFirstTimeLoaded = false
         print("variable size \(String(describing: variableHeights?.count))")
        if variableHeights?[tag] == 0.0{
            variableHeights?[tag]=variableSize
            //collectionView.reloadSections(IndexSet.init())
            collectionView.reloadItems(at: [indexPath])
        }

我传递委托根据网页视图内容调整单元格大小,但是在收到委托后 它看起来像(细胞相互重叠)

enter image description here

这里有任何帮助吗?

1 个答案:

答案 0 :(得分:1)

  

删除文本html lable Give(引导,尾随,顶部和修复高度)的底部约束   并选择heightContraint make height Contraint> =)U应该   计算Text Html

的字符串高度
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

//Calculate the height of the string text  
return size + TextHtmlHeight
}
  

然后单元格将根据文本高度

增加
相关问题