ios - 如何将填充添加到搜索栏 swift ios

标签 ios swift uicollectionviewcell uisearchbar

我正在尝试下移我的搜索栏以与 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
    }

有没有办法以编程方式将搜索栏与单元格的底部单元格对齐? 自定义 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
    }

最佳答案

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

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

已编辑以获取更多信息

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

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

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

关于ios - 如何将填充添加到搜索栏 swift ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49042943/

相关文章:

ios - 使用 [NSFileManager URLForUbiquityContainerIdentifier :] and [NSFileManager ubiquityIdentityToken]? 之间的主要区别是什么

ios - 当想要使用 UISlider 增加 View 大小时,CGAffineTransformRotate 设置为其初始状态

ios - 相机框架的快速、可靠的对焦分数

ios - 将触摸事件传递给 UICollectionViewCell 内容?

ios - 版权键和值不在 info.plist 中

ios - 重置 Firebase 缓存

swift - 等待完成再执行下一步

ios - 卡在 KVO_IS_RETAINING_ALL_OBSERVERS_OF_THIS_OBJECT_IF_IT_CRASHES_AN_OBSERVER_WAS_OVERRELEASED_OR_SMASHED

swift - Firebase 聊天用户正在输入指示器单元格

iphone - 单元格获取其前一个单元格的索引 - Tableview 中的 Collectionview