如何向搜索栏添加填充 swift ios

How to add padding to searchbar swift ios

我正在尝试下移我的搜索栏以与集合视图中其父单元格的底部对齐。

    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
    }

有没有办法以编程方式将搜索栏与单元格的底部单元格对齐? 自定义 xib 编辑器不允许我添加约束。

更新了完整的解决方案

使用编辑器添加约束

编辑代码:

  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
    }

InterfaceBuilder 的 .xib 编辑器确实允许您指定约束。您需要在文件检查器(右侧窗格中的第一个选项卡)中打开 "Use Auto Layout"。

或者,您可以通过编程方式设置约束。

已编辑以获取更多信息

如何向搜索栏添加底部约束:

Select 只是搜索栏。然后点击 .xib window 右下角的添加新约束按钮(它看起来像领带战斗机图标)。点击图中中心框下方的细红线,将值设置为适当的值(可能接近 0),然后通过下拉该值旁边的弹出窗口来验证您将其绑定到的视图。然后点击添加 1 个约束按钮。这应该将搜索栏的底部绑定到其父视图的底部。

所以关键是你只想为搜索框设置相对于其直接父级的约束,在你的情况下这将是单元格的视图,而不管 xib 不知道它会是对于一个单元格。