ios - 使用自定义标题按钮修改 TableView 中的部分?

标签 ios swift uitableview

我正在尝试提供在 TableView 中删除或添加部分的功能。 我在 nib 中创建了一个自定义标题 View ,并向其添加了一个标签和 2 个按钮。 问题是,我无法连接删除或添加部分的点。 到目前为止,这是我的代码:

//Setup Header
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! CustomHeader
    //Configure header...
    header.addBtn.addTarget(self, action:Selector(("add")), for: .touchUpInside)
    header.addBtn.tag = section

    switch section {
    case 0:
        header.sectionLBL.text = "Detail 1"
    case 1:
        header.sectionLBL.text = "Detail 2"
    default:
        break
    }
    return header
}

@IBAction func addButton(sender: UIButton) {
    //Add section code here...
}

@IBAction func delete(sender:UIButton){
    //delete section code here...
}

我还试图弄清楚如何让提交样式与按钮一起使用:

    //Setup Editing Style for table view
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)


    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
//Editing styles for deletion or insertion...
}

最佳答案

您只能将 Storyboard场景或 NIB 连接到它们所属的类。

1) 向 CustomHeader 类添加协议(protocol)并确保该类已分配给 NIB:

protocol CustomHeaderButtonPressDelegate {
    func didPressAdd()
    func didPressDelete()
}

class CustomHeader: UIView {
    var delegate:CustomHeaderButtonPressDelegate?
    @IBAction func addButton(sender: UIButton) {
        delegate?.didPressAdd()
    }

    @IBAction func delete(sender:UIButton){
        delegate?.didPressDelete()
    }
}

2) 将他的 NIB 分配给 IBs Inspector 中的新类

enter image description here

将“类”从 UIView 更改为 CustomHeader

3) 将您的按钮目标连接到 CustomHeaderIBAction

4) 以编程方式设置委托(delegate)

class YourClass: UITableViewController, CustomHeaderButtonPressDelegate {
...
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! CustomHeader
    header.delegate = self
...
}
...
func didPressAdd() {
    //handlePress
}
func didPressDelete() {
//handlePress
}

关于ios - 使用自定义标题按钮修改 TableView 中的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818885/

相关文章:

ios - 注释在动画结束前不可点击

ios - 使用未声明的标识符 'SKSpriteNode'

ios - 有没有办法在点击时存储 pdf 注释?

ios - 使用 NSUserDefaults 保存高分

ios - 从NSMutableArray删除for循环内的对象

ios - 在具有许多其他 View 的自定义 UITableViewCell 中为 UIButton 设置操作

ios - Amplitude 未记录 "applicationWillTerminate"iOS 中写入的事件

ios - 展开可选值/Swift 时意外发现 nil

ios - 如何在 swift 3 中按 tableView 上的搜索键时关闭键盘?

ios - 如何在 uitableview 中动态创建部分