iOS导航栏按钮点击动画异常及自定义UIBarButtonItem尺寸问题
1. 自定义视图UIBarButtonItem尺寸过小修复
系统默认会根据customView的内容自适应大小,没有显式设置尺寸时会出现压缩问题,可通过以下两种方式调整:
- 直接设置自定义按钮的frame
let customBtn = UIButton(type: .system) customBtn.setTitle("按钮文本", for: .normal) customBtn.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) // 显式设置按钮尺寸 customBtn.frame = CGRect(x: 0, y: 0, width: 65, height: 32) // 也可添加内边距适配不同文本长度 customBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) customBtn.sizeToFit() let barItem = UIBarButtonItem(customView: customBtn)
- 用自动布局约束声明尺寸
customBtn.widthAnchor.constraint(equalToConstant: 65).isActive = true customBtn.heightAnchor.constraint(equalToConstant: 32).isActive = true
2. 多个leftBarButtonItems点击状态同步实现
系统原生UIBarButtonItem不会自动同步多个item的点击状态,需要手动控制:
- 将所有左侧栏按钮存储为全局属性,方便统一操作
- 在点击事件中遍历所有按钮,同步修改状态
// 全局存储所有自定义左侧栏按钮 var allLeftBarButtons: [UIButton] = [] @objc func buttonTapped(_ sender: UIButton) { // 同步所有按钮的选中/高亮状态 allLeftBarButtons.forEach { button in button.isSelected = !button.isSelected // 需要同步高亮效果可添加以下代码 // button.isHighlighted = true } // 后续处理业务逻辑 }
建议所有需要自定义样式、交互的bar item都采用自定义视图实现,适配不同iOS版本的兼容性更好,不会出现系统样式异常问题。
内容的提问来源于stack exchange,提问作者Abdul Momen
相关产品推荐
相关产品推荐

