optonaut / ActiveLabel.swift

UILabel drop-in replacement supporting Hashtags (#), Mentions (@) and URLs (http://) written in Swift
MIT License
4.47k stars 686 forks source link

Calculate estimated size #222

Closed mb812 closed 5 years ago

mb812 commented 6 years ago

Hi I'm using ActiveLabel inside each cell of a collection view. With the collection view delegate function, I have to give the size of each cell that will be used. The cell height depends on the filled ActiveLabel text height.

Both this extension don't return the correct real label height, so the collection view cell will clip the text inside it.

The attributedText propriety of the ActiveLabel class don't represent the real layout of the label, resulting in a incorrect height calculation.

        let text = "test"
        let attributes = [ NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 16.0)! ]
        let attributedText = NSMutableAttributedString(string: text, attributes: attributes)
        let textHeight: CGFloat = attributedText.heightForActiveLabel(withConstrainedWidth: width - 115.0)

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 ceil(boundingBox.height)
}

func heightForActiveLabel(withConstrainedWidth width: CGFloat) -> CGFloat {
    let label: ActiveLabel = ActiveLabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.attributedText = self
    label.sizeToFit()
    return label.frame.height
}

}

With a normal UILabel the calculated height is the same of the size that will be occupied.

Is this a bug? Or there is an apposite propriety to get the updated attributetText of an ActiveLabel instance?

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.