0

I'm trying to determine the height of a block of text so that I can set a view to the correct height for a scrollview. The text is placed on the screen in a UILabel. The string is long enough that it will wrap.

I've tried a bunch of different approaches with no success. I'm new to programming, and I can find examples of people doing this in Obj-C, but when I try replicating what they did in Swift, I don't get what they're getting – instead, I consistently get a value of 27.6 (even if I change the font size). Here's my best thinking thus far:

var font : UIFont = UIFont()
var attrs : [NSObject: AnyObject] = [font:UIFont.boldSystemFontOfSize(20.0)]
var theSize = (someObject.someString as NSString).boundingRectWithSize( CGSizeMake(300.0, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attrs, context:nil).size

println(theSize.height)

So, I'm stuck...How do I get the height of this block of text in Swift?

Rich
  • 83
  • 9
  • I usually create a UILabel with one line of text and then multiply it by the number of lines plus some padding. – gran_profaci Jun 04 '15 at 22:35
  • I would do that, but I don't know how many lines long it's going to be. The data is getting loaded at runtime and the length depends on what gets loaded. – Rich Jun 04 '15 at 22:44
  • And I'm assuming you have a variable number of lines? – gran_profaci Jun 04 '15 at 23:01
  • Take a look at this : http://stackoverflow.com/questions/4172615/how-to-find-uilabels-number-of-lines – gran_profaci Jun 04 '15 at 23:02
  • @Rich, is there anything else in your `UIScrollView` or just text? – ABakerSmith Jun 04 '15 at 23:49
  • @ABakerSmith I've got a variable number of UILabels inside the UIScrollView. It's a simple recipe app with a listing of recipe ingredients, so I don't know how many are there for any given recipe I load. – Rich Jun 05 '15 at 02:37
  • @gran_profaci I think I've tried that...I might be missing something, but I'm trying to call boundingRectWithSize to get the size. I'm wondering if I'm passing in the wrong parameters. Admittedly, I don't track with Objective-C syntax, so when I look at that code, I'm not 100% sure I'm translating it correctly. – Rich Jun 05 '15 at 02:44
  • @Rich, sounds like you should be using a `UITableView` if you've got a list. Also, I would recommend you use Auto Layout for the sizing of your `UILabel`s. – ABakerSmith Jun 05 '15 at 08:29

0 Answers0