我正在使用所有属性设置的文本字段, 当编辑和文本超出文本字段中的视图时,它不会调整字体大小
txtTitle.font = [UIFont fontWithName:@"Helvetica" size:15.0f];
[txtTitle setMinimumFontSize:3.0];
[txtTitle setAdjustsFontSizeToFitWidth:YES];
它会在某种程度上调整大小,然后与文本超出视图文本字段
的结果相同答案 0 :(得分:5)
我知道这是一个旧线程,但仍然没有弄清楚。 这是一个错误,以下内容可用作解决方法。 在UITextField上创建一个类别并编写以下方法,并在需要更改字体大小以适合文本字段宽度时调用它。
- (void)adjustFontSizeToFit
{
UIFont *font = self.font;
CGSize size = self.frame.size;
for (CGFloat maxSize = self.font.pointSize; maxSize >= self.minimumFontSize; maxSize -= 1.f)
{
font = [font fontWithSize:maxSize];
CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
CGSize labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
// Keeping the width constant if given text requires more height , decrease the font size.
if(labelSize.height <= size.height)
{
self.font = font;
[self setNeedsLayout];
break;
}
}
// set the font to the minimum size anyway
self.font = font;
[self setNeedsLayout];
}
答案 1 :(得分:4)
谢谢你,Ankit!这个对我有用。我不得不更新一个弃用的方法:sizeWithFont
- (void)adjustFontSizeToFit {
UIFont *font = self.font;
CGSize size = self.frame.size;
for (CGFloat maxSize = self.font.pointSize; maxSize >= self.minimumFontSize; maxSize -= 1.f) {
font = [font fontWithSize:maxSize];
//CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
//CGSize labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text
attributes:@ { NSFontAttributeName: font }];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){size.width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];
CGSize labelSize = rect.size;
// Keeping the width constant if given text requires more height , decrease the font size.
if(labelSize.height <= size.height) {
self.font = font;
[self setNeedsLayout];
break;
}
}
// set the font to the minimum size anyway
self.font = font;
[self setNeedsLayout];
}
答案 2 :(得分:0)
快速答案:
extension UITextField {
func adjustFontSizeToFitHeight(minFontSize : CGFloat, maxFontSize : CGFloat) {
guard let labelText: NSString = text else {
return
}
guard let font: UIFont = self.font else {
return
}
let labelHeight = frame.size.height
guard labelHeight != 0 else {
return
}
// replace with newton's method
for size in minFontSize.stride(to: maxFontSize, by: 0.1) {
let textHeight = labelText.sizeWithAttributes([NSFontAttributeName: font.fontWithSize(size)]).height
if textHeight > labelHeight {
self.font = font.fontWithSize(max(size - 0.1, minFontSize))
return
}
}
self.font = font.fontWithSize(maxFontSize)
}
}