UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: UITextField inside tableFooterView

Forums > iOS

What is the best way to have an UITextField inside a tableFooterView? I tried the following:

let textField = UITextField(frame: .zero)
textField.autoresizingMask = [.flexibleWidth, .flexibleHeight]
textField.font = UIFont.preferredFont(forTextStyle: .subheadline)

textField.borderStyle = .roundedRect
textField.placeholder = "Enter Session ID"

textField.clearButtonMode = .whileEditing

tableView.tableFooterView = textField

This works fine as long as the phone is in portrait mode. After entering landscape mode the textfield is to big. Can anyone explain?

3      

I would set Autolayout constraints and add code to have the footer auto-size based on content which should help you.

I am using this and it works great:

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        if let footer = tableView.tableFooterView {
            let newSize = footer.systemLayoutSizeFitting(CGSize(width: tableView.bounds.width, height: 0))
            footer.frame.size.height = newSize.height
        }
    }

5      

Sadly I don't understand this fully. But it works perfectly :-D

3      

Yea it almost like "one of those things". This method viewWillLayoutSubviews is called when the view has been laid out by its parent which means it has correct size according to AutoLayout or some other rules and now based on that it is time to lay out the subviews (aka set their correct position and sizing).

And because table view footer (and header) don't work with autolayout we need to set the size manually using this implementation.

footer.systemLayoutSizeFitting(CGSize(width: tableView.bounds.width, height: 0)) will get us the needed size for correct AutoLayout. 0 means automatic or (as much as needed) and then we manually set the frame. Not pretty but it works.

Also note of caution: Just a few days ago I wasted a lot of time trying to get auto-sizing UITextView to work in table view header and it was likely impossible and in the end creating custom table view cell subclass worked like a charm.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.