我正在尝试向下移动我的搜索栏,以便在集合视图中与其父单元格的底部对齐。
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
}
答案 0 :(得分:2)
InterfaceBuilder的.xib编辑器确实允许您指定约束。您需要在文件检查器中打开“使用自动布局”(右侧窗格中的第一个选项卡)。
或者,您可以通过编程方式设置约束。
修改了更多信息
如何向搜索栏添加底部约束:
只选择搜索栏。然后点击.xib窗口右下角的Add New Constraints按钮(它看起来像一个领带战斗机图标)。点击图形中心框下方的细红线,将值设置为适当的值(可能接近0)并通过拉下该值旁边的弹出窗口来验证您绑定它的视图。然后点击添加1约束按钮。这应该将搜索栏的底部绑定到其父视图的底部。
所以关键是你只想为搜索框设置相对于其直接父级的约束,这将是你的情况下单元格的视图,不管xib不知道它将是一个细胞