Is it possible to vertically align text inside labels with a “large” frame

前端 未结 8 1612
梦谈多话
梦谈多话 2021-01-01 11:58

In my application I have multiple tableviews with custom cells. Some of the text in the cells are spread out on between 2-4 lines so the height of the label is large enough

8条回答
  •  甜味超标
    2021-01-01 12:43

    In iOS 7 sizeWithFont: is now deprecated! Several solutions like subclassing UILabel have to be adapted.

    My solution for top aligned label text: In a subclass TopVerticalAlignmentLabel : UILabel override drawRect: as follows:

    - (void)drawRect:(CGRect)rect
    {
        CGRect labelStringRect = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)
                                                         options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                      attributes:@{ NSFontAttributeName: self.font, /* further attributes */}
                                                         context:nil];
    
        [super drawTextInRect:CGRectMake(0, 0, self.frame.size.width, labelStringRect.size.height)];
    }
    

提交回复
热议问题