0

I have to extend the size of TextView by based on its text but it have show the issue but I unable to fix it so please help me for fix this issue.I post the code what I am tried.

var size: CGSize = text.sizeWithFont(UIFont.boldSystemFontOfSize(13), constrainedToSize: textSize, lineBreakMode:NSLineBreakMode.ByWordWrapping)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
B.Saravana Kumar
  • 1,208
  • 6
  • 20
  • 48
  • See the (ObjC) solutions and suggestions here: http://stackoverflow.com/questions/19398674/sizewithfont-method-is-deprecated-boundingrectwithsize-returns-an-unexpected-va – vadian Apr 02 '16 at 13:58
  • Ok Thanks. But If you give Swift solution means that is very helpful for me. – B.Saravana Kumar Apr 02 '16 at 14:06

1 Answers1

5

I translated the answer from this ObjC question into Swift; what may be tripping you up is that you need to cast String to NSString.

Swift 4

let text = "Hello"
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let maxSize = CGSize(width: 100, height: CGFloat.greatestFiniteMagnitude)

let size = (text as NSString).boundingRect(with: maxSize,
        options: [.usesLineFragmentOrigin, .usesFontLeading],
        attributes: [NSFontAttributeName:font],
        context: nil)
    .size

Swift 3

let text = "Hello"
let font = UIFont.systemFontOfSize(UIFont.systemFontSize())
let maxSize = CGSize(width: 100, height: CGFloat.max)

let size = (text as NSString).boundingRectWithSize(maxSize,
        options: [.UsesLineFragmentOrigin, .UsesFontLeading],
        attributes: [NSFontAttributeName:font],
        context: nil)
    .size
Kevin
  • 16,696
  • 7
  • 51
  • 68
  • I use This Code Means It shows like "Cannot convert value of type 'UIFont' to expected argument type 'CGSize'".Then I give the Full function here... let text: NSString = message.text! let textSize: CGSize = CGSize(width: 260.0,height: 10000.0) let size = (text as NSString).boundingRectWithSize(UIFont.boldSystemFontOfSize(13), options: [NSStringDrawingOptions.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [NSFontAttributeName:font], context: nil) – B.Saravana Kumar Apr 02 '16 at 14:27
  • Thanks for you help it properly works now...Very very thanks @Kevin – B.Saravana Kumar Apr 02 '16 at 14:37