martin
martin

Reputation: 1974

Swift - toolbar follows tableview when scrolling

In my UITableViewController, my toolbar follows my tableview when I scroll it. My code looks like this:

 override func viewDidLoad() {
        let toolbar: UIToolbar = UIToolbar()
        let checkButton = [UIBarButtonItem(title: "Done", style: .Done, target: self, action: "checkedPress")]
        toolbar.frame = CGRectMake(0, self.view.frame.size.height - 46, self.view.frame.size.width, 48)
        toolbar.sizeToFit()
        toolbar.setItems(checkButton, animated: true)
        toolbar.backgroundColor = UIColor.redColor()
        self.view.addSubview(toolbar)
    }

and it looks like this when I run the app: enter image description here

I want the toolbar to stick to the bottom of the view, how is this achieved?

Any suggestions would be appreciated.

Upvotes: 3

Views: 3115

Answers (2)

Henk-Martijn
Henk-Martijn

Reputation: 2024

You can also embed your TableViewController in a Navigation Controller and show from the storyboard or programmatically a Toolbar. This one also standard sticks to the bottom and stays on top of the Views content and you have some functionality to hide it automatically on some conditions.

enter image description here

You don't have to use your Navigation controller always for navigating, sometimes its a convenient way for doing stuff Xcode makes hard to use without changing your already made Views.

Upvotes: 0

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

The problem is that since you're using a UITableViewController, with self.view.addSubview(toolbar), you've added your toolbar as a subview of your UITableViewController's view, i.e. a UITableView. As a subview of the UITableView, the toolbar will scroll along with the table.

The solution: Use a UIView containing a UITableView instead of using a UITableViewController if you'd like to customize your view controller. That way you can add elements to the view that aren't subviews of your tableview.

Upvotes: 3

Related Questions