Custom UITableViewCell with Partially Bold Text
Trying to implement a UITableView of names similar to the built-in Contacts iPhone app where the first name is in normal font and the last name is bold. A quick google suggests this isn't as easy as it sounds due to the iPhone SDKs lack of rich text support in UILabels.
One of the solutions found recommended using a UIWebView to format the text allowing HTML bold tags to provide the required markup. Correct me if I'm wrong but this seems to be overkill and would have an affect on the performance of the app.
Another solution which I'm trying to investigate more is to create a custom UITableViewCell containing two UILabels side by side with the second label formatted for bold text. This seems straightforward, but I'm not sure how to have the labels auto-size horizontal开发者_开发百科ly to fit the text (up to a certain max width). Is this possible via the Interface Builder or does this need to be done programmatically?
Am I on the right track here or is there a much easier way to achieve this seemingly trivial effect?
I wonder if you should subclass UILabel and do the drawing yourself. Then you could use CGContextSelectFont
, CGContextGetTextPosition
, CGContextSetTextPosition
, CGContextShowText
etc to draw your text.
Select the normal font, set the initial text position, draw your text, advance the text position by a few pixels, select the bold font, draw your bold text, and so on.
I haven't done this myself before, but am thinking of using this solution for one of my applications as well.
It looks like this has been asked a few times on Stack Overflow under various guises. A common solution seems to be the Three20 library's TTStyledTextLabel. Until the iPhone SDK includes an inbuilt rich text label and short of rolling my own, this class looks to be the next best thing.
Edit: Just came across this solution and it looks even better: https://github.com/chrisdevereux/Slash
enter code here NSDictionary *firstNameAttributes = @{ NSFontAttributeName : [UIFont fontWithName:@"Arial" size:20.0],
NSStrokeColorAttributeName : [UIColor blackColor]};
NSDictionary *lastNameAttributes = @{NSFontAttributeName : [UIFont fontWithName:@"Arial-Bold" size:20.0],
NSStrokeColorAttributeName : [UIColor blackColor]};
NSString* first = @"udhaya";
NSString* last = @" chandrika";
NSString *append=[NSString stringWithFormat:@"%@%@",first,last];
cell.textLabel.text = [NSString stringWithFormat:@"%@",append];
NSMutableAttributedString * name =
[[NSMutableAttributedString alloc] initWithString:first attributes:firstNameAttributes];
NSMutableAttributedString * lastName =
[[NSMutableAttributedString alloc] initWithString:last attributes:lastNameAttributes];
[name appendAttributedString:lastName];
[[cell textLabel] setAttributedText:name];
精彩评论