iOS开发:如何调整UISearchBar中取消按钮的垂直位置?
调整UISearchBar取消按钮的垂直位置与标题(iOS 11+)
我刚好碰到过类似的问题,iOS 11把UISearchBar放到navigationItem后,取消按钮的布局逻辑和之前有所不同,给你两个实用的解决方案:
一、调整取消按钮的垂直位置
取消按钮藏在UISearchBar的子视图层级里,我们可以通过遍历子视图定位到它,再通过内边距或视图变换实现垂直偏移:
方法1:调整内容内边距
func adjustCancelButtonVerticalPosition() { // 递归遍历子视图,找到取消按钮 func findCancelButton(in view: UIView) -> UIButton? { for subview in view.subviews { if let cancelBtn = subview as? UIButton, cancelBtn.accessibilityIdentifier == "UISearchBarCancelButton" { return cancelBtn } if let foundBtn = findCancelButton(in: subview) { return foundBtn } } return nil } guard let cancelButton = findCancelButton(in: searchBar) else { return } // 根据需求设置垂直偏移,这里top设为4、bottom设为-4,让按钮整体向上偏移4pt cancelButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0) }
方法2:使用视图变换偏移
如果内边距调整效果不符合预期,也可以直接用变换移动按钮:
if let cancelButton = findCancelButton(in: searchBar) { cancelButton.transform = CGAffineTransform(translationX: 0, y: 4) }
注意:取消按钮是在搜索栏开始编辑后才会显示的,建议在
searchBarDidBeginEditing(_:)代理方法里调用上述代码,确保按钮已经加载完成。
二、修改取消按钮的标题
修改标题有两种简洁的实现方式:
方式1:通过KVC直接获取按钮
// 先显示取消按钮 searchBar.setShowsCancelButton(true, animated: true) // 通过KVC获取按钮并修改标题 if let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton { cancelButton.setTitle("自定义取消", for: .normal) // 还能顺便调整字体、颜色 cancelButton.setTitleColor(.systemBlue, for: .normal) cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) }
方式2:遍历子视图时一并修改
在前面找取消按钮的逻辑里,找到按钮后直接设置标题即可:
if let cancelButton = findCancelButton(in: searchBar) { cancelButton.setTitle("自定义取消", for: .normal) }
内容的提问来源于stack exchange,提问作者Vladimir Vishnyagov
相关产品推荐
相关产品推荐

