How to adjust font size of label to fit the rectangle?

前端 未结 14 705
独厮守ぢ
独厮守ぢ 2020-11-28 07:00

Yeah, there\'s this cool myLabel.adjustsFontSizeToFitWidth = YES; property. But as soon as the label has two lines or more, it won\'t resize the text to anythin

14条回答
  •  抹茶落季
    2020-11-28 07:11

    Niels Castle code work find.

    Here is the same idea with a different implementation.
    My solution is more precise but also much more CPU intensive.

    Add this function to a class who inherit UILabel.

    -(void)fitCurrentFrame{
    
        CGSize iHave = self.frame.size;
    
        BOOL isContained = NO;
        do{
            CGSize iWant = [self.text sizeWithFont:self.font];
            if(iWant.width > iHave.width || iWant.height > iHave.height){
                self.font = [UIFont fontWithName:self.font.fontName size:self.font.pointSize - 0.1];
                isContained = NO;
            }else{
                isContained = YES;
            }
    
        }while (isContained == NO);
    }
    

提交回复
热议问题