Monday, February 23, 2009

IPhone: Dynamically create UIView containing text only

I've been spending some time recently inside the IPhone SDK building some small apps as a learning experience. Today, I came across a scenario that took me some time to figure out. Initially, I was trying to accomplish this in Quartz with little success. After some digging around in the documentation, the solution actually was pretty simple and elegant.

Simply put, I was trying to create a dynamic UIView that had the exact size of a specific letter. Here are the two key pieces of code that allowed me to accomplish it (these are part of UIKit).

1. Before I initialize the new view, I determine what the size should be by calling this function on the string from the controller.

NSString *letter = @"T";
UIFont *font = [UIFont fontWithName:@"MarkerFelt-Thin" size:64];
CGSize letterSize = [letter sizeWithFont:font];
CustomView *customView = [[CustomView alloc] initWithFrame:CGRectMake(0,0,letterSize.width,letterSize.height)];
[self.view addSubview:customView];

2. Then on the drawRect method of the custom UIView, I simply needed to do the following.

UIFont *font = [UIFont fontWithName:@"MarkerFelt-Thin" size:64];
[@"T" drawAtPoint:CGPointMake(0,0) withFont:font];

The duplication of UIFont and String text is here for demonstration purposes only. In my actual implementation I initialize the custom view with both the size and view.

Hope this helps someone out.