0

I have always worked in Objective-C, I have been using Swift for a short time .. I had a UITextView class in Objective-C where I was working on the intrinsicContentSize method.


Objective-C

-(CGSize)intrinsicContentSize {
    if ([self.text length]) return self.contentSize;
    else return CGSizeZero;
}

Now I'm trying to convert my Objective-C code to Swift but I'm having problems with this function ...

 override var intrinsicContentSize: CGSize {
         if text.lenght() {
              return contentSize
          } else {
              return CGSize.zero
          }
    }

text.lenght appears to give me a

Value of type error '(UITextRange) -> String? has no member 'length'

Cœur
  • 37,241
  • 25
  • 195
  • 267
kAiN
  • 2,559
  • 1
  • 26
  • 54
  • See https://stackoverflow.com/questions/24037711/get-the-length-of-a-string the way to retrieve the length of the string is different in Swift – Arik Segal Jan 22 '20 at 12:59
  • @ArikSegal I tried to replace text.length context.count or text.character.count but it keeps giving me the same error .. for this reason I can't understand where I'm wrong – kAiN Jan 22 '20 at 13:01
  • Typo in code: `lenght` → `length` – Cœur Feb 22 '20 at 11:35
  • Does this answer your question? [Get the length of a String](https://stackoverflow.com/questions/24037711/get-the-length-of-a-string) – clearlight Feb 23 '20 at 01:18

2 Answers2

1

try this

override var intrinsicContentSize: CGSize {
    return text.isEmpty ? .zero : contentSize
}

intrinsic content size depends on text length (number of characters in a string) and we return the size that is needed

Vadim Nikolaev
  • 2,132
  • 17
  • 34
0

You can use like it below in swift

override var intrinsicContentSize: CGSize {
     if self.text.count > 0 {
        return contentSize
     } else {
        return CGSize.zero
     }
 }

Hope It will help you.

HardikS
  • 656
  • 3
  • 10