如何添加填充到searchbar swift ios

问题描述 投票:0回答:1

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

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
    }

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

更新了完整的解决方案enter image description here

使用编辑器添加约束

enter image description here

编辑代码:

  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
    }
ios swift uicollectionviewcell uisearchbar
1个回答
2
投票

InterfaceBuilder的.xib编辑器确实允许您指定约束。您需要在文件检查器中打开“使用自动布局”(右侧窗格中的第一个选项卡)。

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

编辑了解更多信息

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.