计算内容的高度

时间:2018-02-05 13:27:47

标签: ios swift xcode uicollectionview uicollectionviewcell

我带出了几个文本块,其中的信息来自json文档。

接下来,我计算这些块的高度,这将指定UICollectionview中单元格的高度 这是代码:

if(indexPath.item == 0){
        var heightContent: CGFloat = 0
        for number in contentArray{
            if(number.switcher == 1){
                let approximateWidthOfTitlePost = view.frame.width - 15 - 15 - 25
                let sizeTitle = CGSize(width: approximateWidthOfTitlePost, height: 2000)
                let attributeTitle = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)]
                let estimatedFrameText = NSString(string: number.content!).boundingRect(with: sizeTitle, options: .usesLineFragmentOrigin, attributes: attributeTitle, context: nil)
                heightContent += estimatedFrameText.height + 20
            }
            if(number.switcher == 2){
                heightContent += 250 + 20
            }
            if(number.switcher == 3){
                let approximateWidthOfFirstCaption = view.frame.width - 15 - 15 - 10
                let sizeFirstCaption = CGSize(width: approximateWidthOfFirstCaption, height: 2000)
                let attributeFirstCaption = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)]
                let estimatedFrameText = NSString(string: number.content!).boundingRect(with: sizeFirstCaption, options: .usesLineFragmentOrigin, attributes: attributeFirstCaption, context: nil)
                heightContent += estimatedFrameText.height
            }
        }
        let approximateWidthOfTitlePost = view.frame.width - 15 - 15 - 10
        let sizeTitle = CGSize(width: approximateWidthOfTitlePost, height: 2000)
        let attributeTitle = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.semibold)]
        let estimatedFrameTitle = NSString(string: (postInfo?.titlePost)!).boundingRect(with: sizeTitle, options: .usesLineFragmentOrigin, attributes: attributeTitle, context: nil)

        return CGSize(width: view.frame.width, height: heightContent + 15 + 30  + 13 + estimatedFrameTitle.height + 15)  

问题是计算出的高度有很宽的值。结果,在屏幕上显示单元格时存在很大差异:
First
Second

这种锚:image.anchor(bottomAnchor, left: self.leftAnchor, bottom: nil, right: self.rightAnchor, topConstant: 15, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 250)

问题:如何更准确地计算身高?

抱歉我的英文

0 个答案:

没有答案