NSAttributedString text position

I sub-classed a UILabel, so I can use this TitleLabel on several places. This TitleLabel has a custom font. The lineheight is set with an NSAttributedString.

This is the drawTextInRect override method:

- (void)drawTextInRect:(CGRect)rect {
    self.text = @"THIS IS A TEST";
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self.text];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.minimumLineHeight = 15.f;
    paragraphStyle.maximumLineHeight = 15.f;

    [attStr addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0,7)];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.text.length)];
    [attStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:TITLE_FONT_NAME size:TITLE_FONT_SIZE] range:NSMakeRange(0, self.text.length)];

    self.attributedText = attStr;

    [super drawTextInRect:rect];

The background colors are added for test purposes. As you can see, the yellow background color has the right position. The text THIS IS should be in the yellow background, but is positioned above the background. TITLE_FONT_SIZE is 15, defined somewhere else.

Anyone knows why this happens?


You are changing the font size, so that if the font is too big the text gets cut. That's normal, change your font size according to the rect size. Make it be something like this:

[attStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:TITLE_FONT_NAME size: MIN(rect.size.height*0.4,rect.size.width*0.4)] range:NSMakeRange(0, self.text.length)];


Not sure which rectangle gets passed to the method. There's nothing in the doc, maybe is the frame and not the view bounds. Try this:

[super drawTextInRect: [self convertRect: rect fromView: nil] ];

Need Your Help

How can I zoom in and zoom out an image programmatically in C#?

c# .net image image-manipulation image-zoom

I would like to be able to zoom (-/+) an image that is placed under a panel. I would like the zoomed version of the image to be displayed within that panel. How can I achieve this in C#?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.