0

I have a UIView, which acts as a container and the width of this container needs to change dynamically based on the longest String. So I want to get CGFloat/CGSize based on String length, is it still possible ?

The method which seems most helpful is now depreciated...

myStringSize : CGSize  = [longestString sizeWithFont:myFont 
                       constrainedToSize:maximumSize 
                       lineBreakMode:self.myLabel.lineBreakMode];

Rather than basing it on a label I would like to base it on a String

Maja
  • 59
  • 1
  • 11
  • Possible duplicate of [How to calculate UILabel width based on text length?](https://stackoverflow.com/questions/3527494/how-to-calculate-uilabel-width-based-on-text-length) – Venk Oct 11 '17 at 11:09
  • @Venkat Thank you for the link, unfortunately it's from 7 years ago, which is why the method is now depreciated :( – Maja Oct 11 '17 at 11:11
  • Check all the answers in that link. Hope this will help you . `yourLabel.intrinsicContentSize.width`. 7 yrs old answer also can give u the solution (`boundingRect`) :p – Venk Oct 11 '17 at 11:18

3 Answers3

0

You have to give Known Width or Height:

extension String {

    func getHeight(with width: CGFloat, font: UIFont) -> CGFloat {
        let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let actualSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil)
        return actualSize.height
    }


    func getWidth(with height: CGFloat, font: UIFont) -> CGFloat {
        let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
        let actualSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil)
        return actualSize.width
    }
}
Mohamed Jaleel Nazir
  • 5,776
  • 3
  • 34
  • 48
0

1 - First OF all define The Max Size That you want MaxWidth

 CGSize constraint = CGSizeMake(MaxWidth, CGFLOAT_MAX);

2- attributes for Your text :

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize:FONT_SIZE], NSFontAttributeName, nil];

3-* This is How to get The paraRect From text:

CGRect paraRect = [text boundingRectWithSize:constraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil];

4-* Finally Get The Size :

CGSize size = paraRect.size;
0

Thank you for your help @Venkat, this is the solution that worked for me

 @objc func containerWidth() -> (CGFloat){
        let containerSize = self.myLabel.intrinsicContentSize
        containerWidth = containerSize.width
        return containerWidth
    }
Maja
  • 59
  • 1
  • 11