Vertically align UILabel

前端 未结 10 1606
故里飘歌
故里飘歌 2020-12-31 10:34

I am trying to vertically align the text in the UILabel view of my app. The problem is that I want the text to be vertically aligned to the top and the size of the label to

10条回答
  •  盖世英雄少女心
    2020-12-31 10:53

    You'll need to subclass UILabel. Try this:

    - (void)drawTextInRect:(CGRect)rect
    {
        CGSize sizeThatFits = [self sizeThatFits:rect.size];
        rect.size.height = MIN(rect.size.height, sizeThatFits.height);
    
        [super drawTextInRect:rect];
    }
    

    As you've discovered, UILabel vertically centers text within its bounds. Here we ask -sizeThatFits for the text block size and uses it to constrain the drawing rectangle passed to UILabel, so that text is drawn from the top of the label bounds.

    You could even support the ignored (sigh) contentMode property like this:

    - (void)drawTextInRect:(CGRect)rect
    {
        CGSize sizeThatFits = [self sizeThatFits:rect.size];
    
        if (self.contentMode == UIViewContentModeTop) {
            rect.size.height = MIN(rect.size.height, sizeThatFits.height);
        }
        else if (self.contentMode == UIViewContentModeBottom) {
            rect.origin.y = MAX(0, rect.size.height - sizeThatFits.height);
            rect.size.height = MIN(rect.size.height, sizeThatFits.height);
        }
    
        [super drawTextInRect:rect];
    }
    

    There's a bunch of other solutions and discussion here: Vertically align text to top within a UILabel

提交回复
热议问题