Jecky Jecky - 2 months ago 6
Objective-C Question

Label doesn't start from top left

I uploaded two images of label "Pick up location" and "Drop location". This labels are set in tableview cell.

In this image :

enter image description here

those two label are set with numberoflines = 3 but text starting from middle

And i want this :

enter image description here

I already did this thing with set property numberofLines = 0 and label height >= of label.
But setting this property I have to find label actual height with text and then according to label height I set other controls.

Sizetofit is not working in this case

I want : Label height is fixed. NumberofLines = 3 and label is starting from top left

Thank you for your help

Answer

Make a subclass of UILabel and call it MyTopAlignedLabel.

Then add this to your MyTopAlignedLabel.m file:

    - (void)drawTextInRect:(CGRect)rect {

        if (self.text) {
            CGSize labelStringSize = [self.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(rect), CGFLOAT_MAX)
                                                             options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                          attributes:@{NSFontAttributeName:self.font}
                                                             context:nil].size;

            CGFloat height = MIN(ceilf(labelStringSize.height), CGRectGetHeight(rect));

            [super drawTextInRect:CGRectMake(0, 0, rect.size.width, height)];

        } else {
            [super drawTextInRect:rect];
        }
    }

Set your label in Interface Builder to be of this class.