UITextField 在编辑时不调整字体大小



>我正在使用设置了所有属性的文本字段,编辑时不会调整字体大小,并且文本在文本字段中超出视图

txtTitle.font = [UIFont fontWithName:@"Helvetica" size:15.0f];
[txtTitle setMinimumFontSize:3.0];
[txtTitle setAdjustsFontSizeToFitWidth:YES]; 

它在一定程度上调整大小,然后与超出视图文本字段的文本结果相同

我知道

这是一个旧线程,但仍然以防万一你没有弄清楚.这是一个错误,以下方法可用作解决方法。在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];
}

谢谢你,安吉特!它对我有用。我不得不更新一个不推荐使用的方法: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];
}

快速回答:

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

最新更新