如何从 TableView“编辑”UI 中删除标题和整个部分?我知道可以在tableView.deleteSections()
的代码中执行此操作,但我需要用户在点击“编辑”按钮时才能执行此操作。
以下是解释:
我正在使用Swift 2。
答案 0 :(得分:1)
让我们首先定义UITableViewHeaderFooterView
的自定义子类。该类将用于在表视图中显示标题。
class HeaderView : UITableViewHeaderFooterView {
var actionHandlerBlock: (Void -> Void)?;
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
let button = HeaderView.SetupButton()
addSubview(button);
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let button = HeaderView.SetupButton()
addSubview(button);
}
func removeButtonTapped(sender: AnyObject) {
actionHandlerBlock?();
}
}
private extension HeaderView {
static func SetupButton() -> UIButton {
let button = UIButton.init();
button.addTarget(self, action: "removeButtonTapped:", forControlEvents: .TouchUpInside)
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitle("Remove section", forState: .Normal)
button.sizeToFit()
return button
}
}
这门课非常简单。它的职责是使用一个额外的视图创建标题视图 - 我们将使用该按钮来检测用户何时想要删除表视图的一部分。
每次用户点击标题视图中的按钮时,都会调用块actionHandlerBlock
。
为了在标题视图中删除用户点击按钮后的部分,我们必须为表视图的委托提供一些自定义逻辑。
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(HeaderView.self, forHeaderFooterViewReuseIdentifier: "header")
//rest of your set up code here
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as! HeaderView
header.actionHandlerBlock = { [section] in
//don't forget to remove section from your data source here
tableView.deleteSections(NSIndexSet(index: section), withRowAnimation: .None)
}
return header
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
在函数tableView:viewForHeaderInSection:
中,我们设置标题视图的actionHandlerBlock
属性。我们只是在每次调用此块时删除节。在调用deleteSections:
方法之前,请务必修改表格视图的数据来源 - 您的数据源必须知道删除该部分才能在数据的numberOfSectionsInTableView:
函数中返回正确数量的部分源。