Can't get UITextField to autoshrink text

后端 未结 11 832
逝去的感伤
逝去的感伤 2020-12-05 14:25

I have a UITextField on a table view cell, and when it\'s text becomes too long I would like the font size to decrease. I want to make it very clear that I am t

11条回答
  •  广开言路
    2020-12-05 14:58

    -(BOOL)sizeFontToFit:(NSString*)aString minSize:(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 = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
    
    while (stringSize.height >= self.frame.size.height)
           {
           if (fontSize <= aMinFontSize) // it just won't fit
               return NO;
    
           fontSize -= 1.0;
           self.font = [self.font fontWithSize:fontSize];
           tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight);
           stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
           }
    
    return YES; 
    }
    

提交回复
热议问题