How to get the height of a UILabel in Swift?

前端 未结 5 933
误落风尘
误落风尘 2020-12-17 15:21

I am a beginner in Swift and I am trying to get the height of a label. The label has multiple lines of text. I want to know the total height it occupies on the screen.

5条回答
  •  一生所求
    2020-12-17 15:59

    Swift 5 ioS 13.2 tested 100%, best solution when the UILabel numberOfLines = 0

    Note, result is rounded. Just remove ceil() if you don't want it.

    If you want to get height -> give storyboard width of UILabel

    If you want to get width -> give storyboard height of UILabel

        let stringValue = ""//your label text
        let width:CGFloat = 0//storybord width of UILabel
        let height:CGFloat = 0//storyboard height of UILabel
        let font = UIFont(name: "HelveticaNeue-Bold", size: 18)//font type and size
    
        func getLableHeightRuntime() -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = stringValue.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
            return ceil(boundingBox.height)
        }
    
        func getLabelWidthRuntime() -> CGFloat {
            let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
            let boundingBox = stringValue.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
            return ceil(boundingBox.width)
        }
    

提交回复
热议问题