Tometoyou
Tometoyou

Reputation: 8376

Stack overflow caused by custom UITextView

I have a UITextView subclass that has the following code:

@IBDesignable class UITextViewFixed: UITextView {
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }

    func setup() {
        textContainerInset = .zero
        textContainer.lineFragmentPadding = 0
        var b = bounds
        let h = sizeThatFits(CGSize(
            width: bounds.size.width,
            height: CGFloat.greatestFiniteMagnitude)
        ).height
        b.size.height = h
        bounds = b
        contentInset = .zero
    }
}

It was taken from this stack overflow answer for producing UITextViews without any text padding. Unfortunately when I call self.view.layoutIfNeeded() on adjusting the container view that holds my text view, a recursive loop occurs. It calls layoutSubviews() and then calls setup() which then calls layoutSubviews() etc. This carries on until it causes a stack overflow. How can I stop this?

Upvotes: 0

Views: 48

Answers (1)

Tometoyou
Tometoyou

Reputation: 8376

I fixed it by removing this bit:

var b = bounds
let h = sizeThatFits(CGSize(
    width: bounds.size.width,
    height: CGFloat.greatestFiniteMagnitude)
).height
b.size.height = h
bounds = b
contentInset = .zero

Upvotes: 1

Related Questions