Getting UILabel's Text Height with adjustsFontSizeToFitWidth
Working on the 1.1 release of Cee-lo today I ran into a task where I needed to position a button underneath a text field. I wanted said button to be positioned relative to the height of the text field. In Actionscript, this task is easy:
theButton.y = theTextField.y + theTextField.textHeight;
+1 abstracted language, no? In objective-c/iOS SDK, the task is slightly more complex. Especially when the UILabel's font size is set to auto adjust (adjustsFontSizeToFitWidth) based on the width of the text field. Here's the working solution below. In this example, the username field on Cee-lo's winner screen is set and the rematch button is positioned under the UILabel based on the text height of the username field. The max font size for the field is 36 and the minimum is 12.
- (void)setUsernameText:(NSString *)theText
{
// assign the text to the username field
self.username.text = theText;
// actualFontSize accepts a pointer to a CGFloat, so define that here
CGFloat fontSize;
// determine the size of the field if we were to show theText
// in it at the original size
CGSize size = [theText sizeWithFont:self.username.font
minFontSize:12.0f
actualFontSize:&fontSize
forWidth:self.username.frame.size.width
lineBreakMode:self.username.lineBreakMode];
// so at this point, size is a frame that defines the bounds
// of the textfield if it were rendered at 36 pt. But now, by reference, fontSize
// contains the actual size of the text field's font after resizing.
// So we use that size to determine how big the field would be
// with that font size:
CGSize computed = [theText sizeWithFont:[UIFont fontWithName:HelveticaNeueBold size:fontSize]];
// position the rematch button under the text field
self.rematch.frame = CGRectMake(20.0f, self.username.frame.origin.y + computed.height + 5, self.rematch.frame.size.width, self.rematch.frame.size.height);
}
September 19th, 2010 | Permalink