Figure out size of UILabel based on String in Swift

后端 未结 11 1553
执笔经年
执笔经年 2020-11-22 13:35

I am trying to calculate the height of a UILabel based on different String lengths.

func calculateContentHeight() -> CGFloat{
    var maxLabelSize: CGSize         


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 14:36

    I found that the accepted answer worked for a fixed width, but not a fixed height. For a fixed height, it would just increase the width to fit everything on one line, unless there was a line break in the text.

    The width function calls the height function multiple times, but it is a quick calculation and I didn't notice performance issues using the function in the rows of a UITable.

    extension String {
    
        public func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : font], context: nil)
    
            return ceil(boundingBox.height)
        }
    
        public func width(withConstrainedHeight height: CGFloat, font: UIFont, minimumTextWrapWidth:CGFloat) -> CGFloat {
    
            var textWidth:CGFloat = minimumTextWrapWidth
            let incrementWidth:CGFloat = minimumTextWrapWidth * 0.1
            var textHeight:CGFloat = self.height(withConstrainedWidth: textWidth, font: font)
    
            //Increase width by 10% of minimumTextWrapWidth until minimum width found that makes the text fit within the specified height
            while textHeight > height {
                textWidth += incrementWidth
                textHeight = self.height(withConstrainedWidth: textWidth, font: font)
            }
            return ceil(textWidth)
        }
    }
    

提交回复
热议问题