【问题标题】:Altering table cell header on action in swift快速更改表格单元格标题
【发布时间】:2020-11-19 12:04:01
【问题描述】:

我的分段表格视图中有一个标题,其中包含一个按钮,点击时会扩展其单元格,我在标题中也有一个向右的箭头,当点击标题时,我想将该箭头图像更改为一个向下的箭头,如何更改该部分的标题?特别是arrowButton

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
        
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: tableView.frame.width - 30, height: 50))
        button.setTitle(tableDataSource[section][0].mod.modType!, for: .normal)
        button.titleLabel?.font = UIFont(name: "Helvetica neue", size: 20)
        button.addTarget(self, action: #selector(headerPressed(sender:)), for: .touchUpInside)
        button.titleLabel?.textAlignment = .left
        
        button.tag = section
        
        let arrowButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        arrowButton.setImage(UIImage(systemName: "chevron.right", compatibleWith: nil), for: .normal)
        header.addSubview(arrowButton)
        
        header.addSubview(button)
        header.backgroundColor = UIColor.green
        
        
        
        return header
    }

@objc func headerPressed(sender: UIButton){
        if(tableDataSource[sender.tag][0].clicked == false){
            tableDataSource[sender.tag][0].clicked = true
        } else {
            tableDataSource[sender.tag][0].clicked = false
        }
        let sections = IndexSet.init(integer: sender.tag)
        tableView.reloadSections(sections, with: .fade)
    }

【问题讨论】:

    标签: ios swift uitableview tableview


    【解决方案1】:

    你需要在viewForHeaderInSection 里面改一下

    let name = tableDataSource[section][0].clicked ? "chevron.right" : "chevron.left"
    arrowButton.setImage(UIImage(systemName:name, compatibleWith: nil), for: .normal)
    

    调用此 tableView.reloadSections(sections, with: .fade) 将完成重新加载工作

    【讨论】:

    • 成功了,我尝试在headerPressed 函数中这样做,谢谢!