iOS开发:为何UICollectionView自定义头视图内的下拉按钮选中后无法修改标题?
核心问题定位
HeaderCell类继承错误:当前定义的HeaderCell仅遵守UIGestureRecognizerDelegate协议,未继承集合视图要求的UICollectionReusableView,不符合补充视图的使用规范。- 持有无效的头部实例:
ViewController中定义的lazy var headerCell = HeaderCell()是独立创建的空白实例,从未被添加到界面上,和集合视图实际渲染、用户交互的头部单元格完全无关。 - 按钮引用错位:触发下拉时,代码从这个无效实例中取按钮赋值给
selectedButton,后续修改标题操作的是这个未显示的控件,自然无法在界面上看到更新。 - 因为之前获取的是无效实例的frame(值全为0),原代码中为了让下拉视图勉强显示,硬编码了大量位置偏移数值,既导致下拉位置错乱,也进一步引发了后续按钮标题更新的问题。
分步修复方案
1. 修正HeaderCell类定义
调整类继承关系,修改代理方法将用户实际点击的按钮实例直接传递出去,避免绕路获取无效对象。
修改后的HeaderCell完整代码:
protocol HeaderCellDelegate: class { func setDropdown() // 将点击的按钮作为参数传给代理,直接拿到实际交互的控件 func tapOnSelection(sender: UIButton) } class HeaderCell: UICollectionReusableView, UIGestureRecognizerDelegate { weak var hDelegate: HeaderCellDelegate? // 选择按钮,设置默认初始标题 @objc lazy var selectionBtn: UIButton = { let button = UIButton(type: .system) button.setTitle("One", for: .normal) button.addTarget(self, action: #selector(changeSelection), for: .touchUpInside) return button }() // 右侧切换功能图标按钮 @objc lazy var oneOrTwo: UIButton = { let button = UIButton() button.setImage(UIImage(named: "oneOff")?.withRenderingMode(.alwaysTemplate), for: .normal) button.addTarget(self, action: #selector(toggleOneOrTwo), for: .touchUpInside) return button }() override init(frame: CGRect) { super.init(frame: frame) // 初始化视图布局:左侧为选择按钮,右侧为功能图标,点击按钮弹出下拉列表 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) 未实现") } // MARK: - 按钮事件响应 @objc func toggleOneOrTwo(_ sender: Any) { self.hDelegate?.setDropdown() } @objc func changeSelection(sender: UIButton) { // 将实际触发点击的按钮实例通过代理传递给VC self.hDelegate?.tapOnSelection(sender: sender) } }
2. 修正ViewController逻辑
- 删除无用的孤立头部实例
lazy var headerCell = HeaderCell() - 调整代理方法实现,直接使用代理返回的按钮实例作为
selectedButton - 计算按钮在窗口上的绝对坐标,移除原来为了适配无效frame硬编码的位置偏移
修改后的核心代码片段:
class CellClass: UITableViewCell { } class ViewController: UICollectionViewController, UIGestureRecognizerDelegate { let transparentView = UIView() let tableView = UITableView() var dropdownDataSource: [String] = ["One", "Two"] var selectedButton = UIButton() fileprivate let headerCellId = "headerCellId" // 已删除无用的孤立headerCell实例 override func viewDidLoad() { super.viewDidLoad() // 注册集合视图头部补充视图 self.collectionView.register(HeaderCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerCellId) // 初始化下拉列表的表格配置 tableView.delegate = self tableView.dataSource = self tableView.register(CellClass.self, forCellReuseIdentifier: "Cell") } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerCellId, for: indexPath) as! HeaderCell header.backgroundColor = .groupTableViewBackground header.hDelegate = self return header default: fatalError("未知的补充视图类型") } } // 下拉透明背景视图配置 func addTransparentView(frames: CGRect) { let window = UIApplication.shared.keyWindow transparentView.frame = window?.frame ?? self.view.frame self.view.addSubview(transparentView) tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height, width: frames.width, height: 0) self.view.addSubview(tableView) tableView.layer.cornerRadius = 5 transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9) tableView.reloadData() let tapgesture = UITapGestureRecognizer(target: self, action: #selector(removeTransparentView)) transparentView.addGestureRecognizer(tapgesture) transparentView.alpha = 0 UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: { self.transparentView.alpha = 0.5 // 下拉列表自然落在按钮正下方,移除之前硬编码的错位偏移 self.tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height + 5, width: frames.width, height: CGFloat(self.dropdownDataSource.count * 50)) }, completion: nil) } @objc func removeTransparentView() { let frames = selectedButton.frame UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: { self.transparentView.alpha = 0 self.tableView.frame = CGRect(x: frames.origin.x, y: frames.origin.y + frames.height, width: frames.width, height: 0) }, completion: nil) } } extension ViewController: HeaderCellDelegate { func setDropdown() { // 预留扩展逻辑 } func tapOnSelection(sender: UIButton) { // 直接将用户实际点击的按钮存为选择目标 selectedButton = sender // 转换按钮在窗口上的绝对坐标,保证下拉列表对齐按钮位置 let buttonAbsoluteFrame = sender.convert(sender.bounds, to: nil) addTransparentView(frames: buttonAbsoluteFrame) } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dropdownDataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = dropdownDataSource[indexPath.row] cell.textLabel?.font = UIFont.openSansFontOfSize(14) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let title = self.dropdownDataSource[indexPath.row] // 此时selectedButton是界面上实际显示的按钮,设置标题即可正常刷新UI selectedButton.setTitle(title, for: .normal) removeTransparentView() } }
内容的提问来源于stack exchange,提问作者learningswift
相关产品推荐
相关产品推荐

