Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the blank text container on empty UITextView

I've already set the properties textContainerInset and lineFragmentPadding to zero as seen on this code thanks to this removing the padding and margin via this SO answer.

// this is inside a UITextView Subclass
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.textContainerInset = .zero
    self.textContainer.lineFragmentPadding = 0
}

Here's how the UITextView renders when it has text

enter image description here

Here it is with multiple lines

enter image description here

Here's how it renders without text

enter image description here

Is it possible to make the height 0 if the UITextView's text is empty?

Edit:

  1. There is no constraint being used on the UITextView and I'm not planning to set a height constraint as I want this UITextView to automatically resize depending on the text being set into it

  2. This is a isScrollEnabled = false UITextView inside a UITableViewCell, which automatically resizes depending on the data fetched from the api server.

About:

Language: Swift 3.2

IDE: Xcode 9.2

like image 724
Zonily Jame Avatar asked Sep 16 '25 10:09

Zonily Jame


1 Answers

Thanks to uhuru's answer I've formulated an answer to the code of mine that wouldn't need too much of an overhaul.

First I've setup a height constraint for the UITextView programatically.

// outside the scope
var contentTextViewConstraint: NSLayoutConstraint?

// inside awakeFromNib
self.contentTextViewConstraint = NSLayoutConstraint(
    item: self.lblContent,
    attribute: NSLayoutAttribute.height,
    relatedBy: NSLayoutRelation.equal,
    toItem: nil,
    attribute: NSLayoutAttribute.notAnAttribute,
    multiplier: 1,
    constant: 0)
self.contentTextViewConstraint?.isActive = false

Then activate/deactivate the constraint depending on the String

// inside the setup
let contentText: String = model.contentText
self.tvContent.text = contentText
self.contentTextViewConstraint?.isActive = contentText.isEmpty
like image 162
Zonily Jame Avatar answered Sep 18 '25 08:09

Zonily Jame