Aashish Nagar
Aashish Nagar

Reputation: 1227

Getting wrong text height?

I am using below code to determine the hight of text , it works fine for small text but if text is large it gives me wrong height(too much space at bottom of textview) how to fix that.

    let textView = UITextView (frame: CGRectMake(0,0,maxWidth, 10))
    textView.font = font
    textView.text = text
    //textView.textContainerInset = UIEdgeInsetsZero

    let fixedWidth = textView.frame.size.width
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
    var newFrame = textView.frame
    newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    textView.frame = newFrame;
    return textView.frame.height

Upvotes: 0

Views: 1111

Answers (3)

Reinier Melian
Reinier Melian

Reputation: 20804

Try with this method

static func neededHeigthForText(text:String,font:UIFont,maxWidth:CGFloat) ->CGFloat
{
    let options : NSStringDrawingOptions = [.usesLineFragmentOrigin,.usesFontLeading]
    let style : NSMutableParagraphStyle = NSMutableParagraphStyle()
    style.lineBreakMode = .byWordWrapping

    let textAttributes = [NSFontAttributeName:font]

    let size = NSString(string: text).boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude) , options: options, attributes: textAttributes, context: nil).size

    return size.height
}

I hope this helps you

Upvotes: 0

Ganesh Manickam
Ganesh Manickam

Reputation: 2139

Use an extension on String

extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return boundingBox.height
    }
}

and also on NSAttributedString (which is very useful at times)

extension NSAttributedString {
    func height(withConstrainedWidth width: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

        return boundingBox.height
    }

    func width(withConstrainedHeight height: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

        return boundingBox.width
    }
}

Upvotes: 0

Chanchal Warde
Chanchal Warde

Reputation: 983

This will be your text height in textview.

let textView = UITextView (frame: CGRectMake(0,0,maxWidth, 10))
textView.font = font
textView.text = text

let height = textView.conentSize.height

Upvotes: 1

Related Questions