蓝天,小湖,湖水中一方小筑

Change font size of UITextView dynamically

I am working on a UITextView related problem recently, the widget, which have a fixed size, but need to show all content passed in. The text passed in have different length, so the font size should be different. The code snippet below will change the font size dynamically based on the text.

// Set the text before setting font size
my_text_view.text = foo_text;

// Set the default font name and size
int pre_defined_font_size = 14;
my_text_view.font = [UIFont fontWithName:@"Helvetica" size:pre_defined_font_size];

// Change the font size if needed
if (my_text_view.contentSize.height > my_text_view.frame.size.height) {
    int adjust_font_size = 1;
    while (my_text_view.contentSize.height > my_text_view.frame.size.height) {
        my_text_view.font = [UIFont fontWithName:@"Helvetica" size:pre_defined_font_size-adjust_font_size];
        adjust_font_size++;
    }
}

There is a comparison between content height and frame height. If the content is higher than the frame, the font size will be reduced, and check again.