UIView dynamic height depending on Label Height

后端 未结 6 1006
再見小時候
再見小時候 2021-01-15 05:35

I have a Label which takes dynamicaly some data from database. These data are strings which can sometimes be 3-4-5 rows etc. So this labe is inside a UIView.



        
6条回答
  •  无人共我
    2021-01-15 05:55

    first calculate the size of label with the text it contains, using this function

    func calculateSizeOfLabel(text:String,labelWidth:CGFloat,labelFont:UIFont)->CGSize{
            let constrainedSize = CGSizeMake(labelWidth , 9999)
    
            var attributesDictionary:[String:AnyObject] = [:]
    
                attributesDictionary = [NSFontAttributeName:labelFont] as [String:AnyObject]
    
    
    
            let string:NSMutableAttributedString = NSMutableAttributedString(string:text, attributes:attributesDictionary)
    
            var boundingRect = string.boundingRectWithSize(constrainedSize, options:.UsesLineFragmentOrigin, context:nil)
    
            if (boundingRect.size.width > labelWidth) {
                boundingRect = CGRectMake(0,0, labelWidth, boundingRect.size.height);
            }
    
    
        return boundingRect.size
    }
    

    and then apply the height of returned size to the UIView like this

        let labelText = description.text
        let labelWidth = description.bounds.width
        let labelFont = description.font
        let calculatedHeight = calculateSizeOfLabel(labelText,labelWidth:labelWidth,labelFont:labelFont).height 
        DescView.frame = CGRectMake(DescView.frame.origin.x, DescView.frame.origin.y, DescView.bounds.width,calculatedHeight)
    

提交回复
热议问题