【问题标题】:Resizing UICollectionViewCell调整 UICollectionViewCell 的大小
【发布时间】:2018-01-16 23:33:43
【问题描述】:

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

1 .标题 webview 包含帖子标题(如果有) 2. Imageview 包含发布图片(如果可用) 3 .Text webview 包含帖子文本(如果有)

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

我希望我的 UIcollectionViewCell 根据单元格数据调整大小。以前我是覆盖

 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)
}

在我的视图控制器类中

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

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

 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])
        }

我通过委托根据网络视图内容调整单元格的大小,但在收到委托后 它看起来像(单元格相互重叠)

这里有什么帮助吗?

【问题讨论】:

  • 使用堆栈视图在隐藏图像或网页视图时很有用

标签: ios swift3 uicollectionview uicollectionviewcell


【解决方案1】:

删除文本 html 标签 Give(Leading, Trailing,top 和 fix height) 的底部约束 并选择 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
}

然后单元格会根据文字高度增加

【讨论】:

  • 以前我是通过从 html 中展开字符串来计算大小,但我在底部留了空间@Ramesh
  • 这不是标签,是网页视图
  • 我得到了 html,它可能是外部链接、视频或任何 html 文档@Ramesh
  • @Mansuu.... 如果您想在 webview 中显示完整内容并根据内容增加单元格高度您需要增加 webView 的内容大小并将该高度添加到单元格高度的大小.你可以看看这个stackoverflow.com/questions/32548771/…
  • 我尝试使用它,但我使用单独的控制器类和 UICollectionViewCell 类。我曾经通过将委托从 UICollectionViewCell 发送到控制器类来做到这一点,但是发送委托需要很长时间,当接收到委托并且重新加载特定单元时,单元相互重叠@Ramesh
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多