Search code examples
iosobjective-cswiftuitextviewintrinsic-content-size

UITextView Class, intrinsicContentSize issue from Objective-C to Swift


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'


Solution

  • 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