Find the number of characters that fits in a UITextView with constant width and height with a given string?

后端 未结 4 1225
后悔当初
后悔当初 2021-01-05 00:09

In my application I need to set Read more into the text view if text input is large.so my approach is to find the range of string that would fit in the text view and append

4条回答
  •  爱一瞬间的悲伤
    2021-01-05 01:00

    It's a bit complicated, because some letters are wider than others. But you can check the width of your string by using the sizeWithAttributes-method:

    var yourString: String = textField.text
    let myString: NSString = originalString as NSString
    
    //Set your font and add attributes if needed.
    let stringSize: CGSize = myString.sizeWithAttributes([NSFontAttributeName: yourFont])
    

    Now you receive a CGSize and you can check if the width is wider than your textfield.

    if(sizeOfYourTextfield < stringSize){
      //String is too large for your UITextField
    }
    

提交回复
热议问题