Vertically Align UILabel text with constraints and no wrap (auto layout, single line)

前端 未结 4 1635
深忆病人
深忆病人 2021-02-05 13:19

So I have my view setup in IB such that this text label aligns with the top of the thumbnail via constraints.

\"ente

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 13:34

    So I found a workaround. It's a little dicey, but it works.

    So what I did was add a height constraint to my line of text in IB, and grab a reference to that in my view.

    Then in layoutSubviews, I update my constraint height based on the size of the font, which I have to calculate:

    - (void)layoutSubviews {
        if (self.titleLabel.text) {
            CGFloat actualFontSize;
            CGSize titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font minFontSize:9.0 actualFontSize:&actualFontSize forWidth:self.titleLabel.frame.size.width lineBreakMode:NSLineBreakByTruncatingTail];
            CGRect lineBox = CTFontGetBoundingBox((__bridge CTFontRef)([UIFont fontWithName:@"ProximaNova-Regular" size:actualFontSize]));
            self.titleHeightConstraint.constant = lineBox.size.height;
        }
        [super layoutSubviews];
    }
    

    At first I was just setting it to the actual font size, but even with an adjustment (*1.2) it was still clipping the smaller font sizes. The key was using CTFontGetBoundingBox with the font size determined from my calculation.

    This is pretty unfortunate, and I'm hoping there's a better way. Perhaps I should switch to wrapping.

提交回复
热议问题