更改字体大小以适合UITextView

时间:2014-02-01 00:13:31

标签: ios uitextview

我在Storyboard中设置了UITextView。它设置为定义的大小。我希望能够根据文本的大小来更改字体的大小。用户无法编辑文本视图,只需更新一次。知道怎么做吗?

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:2)

在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;
          }

  }

答案 2 :(得分:0)

迅速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)
}