how to add subview at specific point in the view

562 Views Asked by At

I'm adding a imageView and UISearchController.searchBar to tableView.tableHeaderView. but don't find the correct way to show the searchBar after the Image.

    let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 333))
    let image = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 269))
    image.image = #imageLiteral(resourceName: "map")
    view.addSubview(image)
    view.insertSubview(searchController.searchBar, at: 1)//insertSubview(searchController.searchBar, belowSubview: image)
    self.tableView.tableHeaderView = view

but the result is this.enter image description here and the desired result is this. enter image description here

2

There are 2 best solutions below

1
On

Try giving search bar frame if you do not want to use autolayout

 searchBar?.frame = CGRect(x: 0, y: view.frame.size.height-searchBar!.frame.size.height  , width: UIScreen.main.bounds.width, height: searchBar?.frame.size.height ?? 44)


If you are using auto-layout add bottom constraint to searchbar.
    view.addSubview(searchBar!)
searchBar!.translatesAutoresizingMaskIntoConstraints = false
searchBar!.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
searchBar!.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
searchBar!.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchBar!.heightAnchor.constraint(equalToConstant: 44).isActive = true
0
On

If you want to add search bar at the bottom of your view You can add search bar programmatically and pin it to the bottom of your view

view.addSubview(searchBar)

searchBar.bottomAnchor.constraint(equalTo: view.trailingAnchor).isActive =true
searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchBar.heightAnchor.constraint(equalToConstant: 50).isActive = true

The simplest way