2010-05-04 26 views

risposta

7

Prova questa:

NSInteger lengthThreshold = 200; 
if([ textView.text length ] > lengthThreshold) { 
    NSInteger newSize = ... //calculate new size based on length 

    [ textView setFont: [ UIFont systemFontOfSize: newSize ]]; 
} 
11

Il problema con la risposta accettata è che si deve indovinare il numero di caratteri (la lunghezza della stringa) necessari per riempire il campo, e che si differenzia dal tipo di carattere per carattere. Qualcosa del genere, una categoria su UITextView, dovrebbe funzionare.

#import "UITextView+Size.h" 

#define kMaxFieldHeight 1000 

@implementation UITextView (Size) 

-(BOOL)sizeFontToFitMinSize:(float)aMinFontSize maxSize:(float)aMaxFontSize { 

float fudgeFactor = 16.0; 
float fontSize = aMaxFontSize; 

self.font = [self.font fontWithSize:fontSize]; 

CGSize tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight); 
CGSize stringSize = [self.text sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; 

while (stringSize.height >= self.frame.size.height) { 

    if (fontSize <= aMinFontSize) // it just won't fit, ever 
     return NO; 

    fontSize -= 1.0; 
    self.font = [self.font fontWithSize:fontSize]; 
    tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight); 
    stringSize = [self.text sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; 
} 

return YES; 
} 

@end 
+0

Mi piace molto questo approccio. Se qualcuno ha problemi ad usarlo, ecco cosa faccio: 'if (! [MainContent sizeFontToFitMinSize: 12.0 maxSize: 20.0]) {NSLog (@" il contenuto non si adatta! "); } ' – dchakarov

0

Implementazione di Swift 4 ispirata alla risposta di @Jane Sales.

Per il calcolo della larghezza e dell'altezza disponibili, è necessario prendere in considerazione anche i possibili margini verticali e orizzontali (textContainerInset e textContainer.lineFragmentPadding).

Ecco una spiegazione migliore di come il lavoro margini sui UITextView: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TextUILayer/Tasks/SetTextMargins.html

Se la vista testo può ridimensionare, allora dobbiamo anche forzare un layout in modo che possiamo calcolare la dimensione del carattere in base a più grande dimensione possibile vista del testo. In questo caso viene considerata solo l'altezza (layout solo se l'altezza del testo richiesta è maggiore dell'altezza disponibile originale).

import UIKit 

extension UITextView { 

    func adjustFontToFitText(minimumScale: CGFloat) { 
     guard let font = font else { 
      return 
     } 

     let scale = max(0.0, min(1.0, minimumScale)) 
     let minimumFontSize = font.pointSize * scale 
     adjustFontToFitText(minimumFontSize: minimumFontSize) 
    } 

    func adjustFontToFitText(minimumFontSize: CGFloat) { 
     guard let font = font, minimumFontSize > 0.0 else { 
      return 
     } 

     let minimumSize = floor(minimumFontSize) 
     var fontSize = font.pointSize 

     let availableWidth = bounds.width - (textContainerInset.left + textContainerInset.right) - (2 * textContainer.lineFragmentPadding) 
     var availableHeight = bounds.height - (textContainerInset.top + textContainerInset.bottom) 

     let boundingSize = CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude) 
     var height = text.boundingRect(with: boundingSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil).height 

     if height > availableHeight { 
      // If text view can vertically resize than we want to get the maximum possible height 
      sizeToFit() 
      layoutIfNeeded() 
      availableHeight = bounds.height - (textContainerInset.top + textContainerInset.bottom) 
     } 

     while height >= availableHeight { 
      guard fontSize > minimumSize else { 
       break 
      } 

      fontSize -= 1.0 
      let newFont = font.withSize(fontSize) 
      height = text.boundingRect(with: boundingSize, options: .usesLineFragmentOrigin, attributes: [.font: newFont], context: nil).height 
     } 

     self.font = font.withSize(fontSize) 
    } 

} 
Problemi correlati