0

I'm trying to shift down my searchbar to align with the bottom of its parent cell in a collection view.

enter image description here

    if(searchBarCellId == widgets[indexPath.item]){
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: searchBarCellId, for: indexPath) as! SearchBarCell
        cell.backgroundColor = UIColor.white

        cell.searchBar.backgroundImage = UIColor.white.image()
        cell.searchBar.tintColor = UIColor.gray
        let textFieldInsideSearchBar = cell.searchBar.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.backgroundColor = UIColor.lightGray

        return cell
    }

Is there a way to align the searchbar with the bottom cell of the cell programatically? The custom xib editor does not allow me add constraints.

Updated with the full solution enter image description here

Added constraint using editor

enter image description here

Edited codes:

  if(searchBarCellId == widgets[indexPath.item]){
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: searchBarCellId, for: indexPath) as! SearchBarCell
        cell.backgroundColor = UIColor.white
        let frameWidth = UIScreen.main.bounds.width
        let frameHeight = UIScreen.main.bounds.width*0.2

        cell.searchBar.frame=CGRect(x: 0, y: frameHeight*0.47, width: frameWidth*0.7, height: frameHeight*0.5)
        cell.searchBar.backgroundImage = UIColor.white.image()
        cell.searchBar.tintColor = UIColor.gray
        let textFieldInsideSearchBar = cell.searchBar.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.backgroundColor = UIColor.lightGray

        return cell
    }
Ng Zhong Qin
  • 1,211
  • 2
  • 15
  • 28

1 Answers1

2

InterfaceBuilder's .xib editor does indeed let you specify constraints. You need to turn on "Use Auto Layout" in the File Inspector (first tab in the right side pane).

Alternatively, you may set up constraints programmatically.

Edited for more info

How to add a bottom constraint to the search bar:

Select just the search bar. Then tap on the Add New Constraints button at bottom right of the .xib window (it looks like a tie fighter icon). Tap on the thin red line below the center box in the graphic, set the value to something appropriate (probably close to 0) and verify the view you're binding it to by pulling down the popup next to that value. Then tap the Add 1 Constraint button. That should bind the bottom of the search bar to the bottom of its parent view.

So the point is you just want to set up constraints for the search box relative to its immediate parent, which will be the view of the cell in your case, regardless that the xib doesn't know it's going to be for a cell.

Smartcat
  • 2,834
  • 1
  • 13
  • 25