[英]What method would you recommend for a text box , where the text stays inside bounds and decrease font size to stay inside bounds
我需要一个文本框,该文本框需要允许用户在文本框中输入文本,并且文本停留在文本框的边界之内。如果用户输入的文本过多,它将减小字体以使其适合文本框界限。 我不知道哪个对象可以满足此要求。
有趣的是,我只是实现了这一点。 这是我的操作方式:
- (void)fitTextView {
CGFloat height = [[UIScreen mainScreen] bounds].size.height - 16;
_fontSize = 96;
_text.font = [UIFont fontWithName:_fontName size:_fontSize];
while (height < _text.contentSize.height) {
if (_fontSize < 20) {
break;
}
_fontSize -= 0.5;
_text.font = [UIFont fontWithName:_fontName size:_fontSize];
}
while (height > _text.contentSize.height) {
if (_fontSize > 96) {
break;
}
_fontSize += 0.5;
_text.font = [UIFont fontWithName:_fontName size:_fontSize];
}
}
- (void)textViewDidChange:(UITextView *)textView {
[self fitTextView];
}
但是,我的代码存在一些问题,如果您输入的速度足够快,则正在键入的文本会出现一些反弹。 希望获得有关如何解决该问题的反馈。
希望这可以帮助!
[编辑]更多代码。
_fontSize = 96;
_fontName = @"Helvetica";
_text = [[UITextView alloc] initWithFrame:self.view.bounds];
_text.autocapitalizationType = UITextAutocapitalizationTypeNone;
_text.autocorrectionType = UITextAutocorrectionTypeNo;
_text.delegate = self;
_text.text = @"";
_text.font = [UIFont fontWithName:_fontName size:_fontSize];
_text.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
_text.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
[self.view addSubview:_text];
记住要声明您的类实现了UITextViewDelegate
协议。
我假设您正在使用UITextField(正如您所说的那样是一个文本框。
所以你可以使用以下
[yourTextField setMinimumFontSize:7.0];
[yourTextField setAdjustsFontSizeToFitWidth:YES];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.