One label, two different fonts?

I need to format the text on a label like this:

username: text from this user. This will create additional lines of text to be displayed incl. and so on.

Where "username" is in bold. This will go into the UILabel which is in the custom cell of the table. Is there a way to get this type of layout?

+2


a source to share


4 answers


For this relatively simple case, you can fake it. You have a label with a bold username and another plain text label in the same position. Insert enough spaces before the plain text to leave room for the username. You can use the UIStringDrawing methods to measure bold text and spaces.



CGSize usernameSize = [theUsername sizeWithFont:theBoldUsernameFont];
CGSize spaceSize = [@" " sizeWithFont:thePlainCommentFont];
NSString *indentedComment = [NSString stringWithFormat:@"%*s%@" , (int)ceil( usernameSize.width / spaceSize.width ) , "" , theComment];

      

+2


a source


If you are using a simple UILabel it is not available. Use two labels for this task.



+1


a source


You need to use a UIWebView or CoreText to do this kind of rich text layout. WebView has a lot of overhead, but it is the most flexible and you cannot use it efficiently in a UITableView cell. CoreText is low level and not as well documented. You can align the table view and just lay out the table with CSS and HTML in a web view and this is how I do it.

0


a source


You can still use the UITableViewCell, but the cell uses the UIWebView for viewing. Set up your own subclass of cells with a smart setter method that allows you to send nsstrings to a method, turning it into a fairly formatted representation.

0


a source







All Articles