MDCOutlinedTextArea difficulties in settings up height and margins

1k Views Asked by At

I'm creating a MDCOutlinedTextArea and adding it to a container view, wit the following code:

   let textArea = MDCOutlinedTextArea(frame: container.frame)
    textArea.label.text = placeholder
    textArea.placeholder = placeholder
    let fontSize: CGFloat = 14
    let font = UIFont(name: GlobalVariables.FONT_NAME, size: fontSize)!
    textArea.label.font = font
    textArea.textView.font = font


    textArea.sizeToFit()


    container.addSubview(textArea)
    textArea.bindFrameToSuperviewBounds()

The bindFrameToSuperViewBounds method is an extension method that makes exactly that:

    func bindFrameToSuperviewBounds(_ margin : CGFloat = 2) {
    guard let superview = self.superview else {
        print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.")
        return
    }

    self.translatesAutoresizingMaskIntoConstraints = false
    self.topAnchor.constraint(equalTo: superview.topAnchor, constant: margin).isActive = true
    self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: margin).isActive = true
    self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: margin).isActive = true
    self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: margin).isActive = true
    //self.heightAnchor.constraint(equalToConstant: superview.frame.size.height).isActive = true

}

Well, the problem is that the text area is not using the whole height of the container view:

enter image description here

As you can see in the picture, the container is bigger as the text area, but the text area refuses to grow.

I managed to make it bigger by setting the number of rows:

let numberOfRows = container.frame.height / font.lineHeight
  textArea.minimumNumberOfVisibleRows = numberOfRows

Although that code is not working well, because the calculation of rows returns more rows than needed. I don't know really how to calculate the number of rows the text area has.

Another problem that I have is that I can't set margins to the text area. As you can see in the source code, I try to give the text area some margin using the constraints. It seems to work for the top and leading constraint, but not for the trailing and maybe the bottom constraint.

Some ideas?

1

There are 1 best solutions below

0
On

Setting up preferredContainerHeight of MDCOutlinedTextArea object to any CGFloat value worked for me. For example:

textArea.preferredContainerHeight = 200.0