Can't get UITextField to autoshrink text

后端 未结 11 827
逝去的感伤
逝去的感伤 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

    My humble solution for this problem was this.... (find the proper size of font on my own - to fit the size of frame) I made it inside delegate method of shouldChangeCharactersInRange:replacementString:

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    
     {
    
        // bla bla ... anything inside method you want to do
    
        // reset font size of textfield
        textField.font = [FONT_PROXY fontNormalOfSizeNormal];
    
        CGFloat widthOfText = [textField.text sizeWithAttributes:@{NSFontAttributeName:textField.font}].width;
        CGFloat widthOfFrame = textField.frame.size.width;
    
        // decrease font size until it fits (25 is constant that works for me)
        while((widthOfFrame - 25) < widthOfText){
            CGFloat fontSize = textField.font.pointSize;
            textField.font = [textField.font fontWithSize:fontSize - 0.5f];
             widthOfText = [textField.text sizeWithAttributes:@{NSFontAttributeName:textField.font}].width;
             widthOfFrame = textField.frame.size.width;
        }
    
    
      }
    

提交回复
热议问题