调整字体大小以适应UITextView

7

我在Storyboard中设置了一个UITextView,它有固定的大小。我想根据文本的长度来改变字体的大小。这个文本视图不允许用户编辑,并且只需更新一次。你有什么好的想法吗?

3个回答

8

UITextField(单行输入框)有adjustsFontSizeToFitWidthminimumFontSize属性。而对于UITextView,您需要自己编写代码实现。

static const CGFloat MAX_FONT_SIZE = 16.0;
static const CGFloat MIN_FONT_SIZE = 4.0;

@interface MyViewController ()

// I haven't dealt with Storyboard / Interface builder in years,
// so this is my guess on how you link the GUI to code
@property(nonatomic, strong) IBOutlet UITextView* textView;

- (void)textDidChange:(UITextView*)textView;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.textView addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.textView.font = [UIFont systemFontOfSize:MAX_FONT_SIZE];
}

- (void)textDidChange:(UITextView*)textView
{
    // You need to adjust this sizing algorithm to your needs.
    // The following is oversimplistic.
    self.textView.font = [UIFont systemFontOfSize:MAX(
        MAX_FONT_SIZE - textView.text.length, 
        MIN_FONT_SIZE
    )];
}

@end

5

这在 Swift 5 中可以正常工作:

  func resizeFont(_ textView: UITextView) {
    if (textView.text.isEmpty || textView.bounds.size.equalTo(CGSize.zero)) {
              return;
          }

          let textViewSize = textView.frame.size;
          let fixedWidth = textViewSize.width;
    let expectSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)));

          var expectFont = textView.font;
          if (expectSize.height > textViewSize.height) {
            while (textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height > textViewSize.height) {
              expectFont = textView.font!.withSize(textView.font!.pointSize - 1)
                  textView.font = expectFont
              }
          }
          else {
            while (textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height < textViewSize.height) {
                  expectFont = textView.font;
                textView.font = textView.font!.withSize(textView.font!.pointSize + 1)
              }
              textView.font = expectFont;
          }

  }

0

Swift 5+

func resizeFont(_ textView: UITextView) {
    textView.layoutIfNeeded()
    let textCount = textView.text.count
    let maxFontSize: CGFloat = max(Font.Size.section.rawValue - CGFloat(textCount), Font.Size.large.rawValue)
    textView.font = Font.primary.of(size: maxFontSize)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接