我有一系列可扩展按钮,所有按钮均具有相同的标题“打开”。我希望每个按钮都具有各自的名称,因为它们都具有自己的功能。我该如何将每个按钮标题设置为独特的内容?我是否必须自己构建每个按钮并离开可扩展数组?
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let button = UIButton(type: .system)
button.setTitle("Open", for: .normal)
button.setTitleColor(.black, for: .normal)
button.backgroundColor = UIColor.lightGray
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
button.addTarget(self, action: #selector(handleExpandClose), for: .touchUpInside)
button.tag = section
return button
}
var showIndexPaths = true
@objc func handleExpandClose(button: UIButton) {
print("trying to expand and close section")
print(button.tag)
let section = button.tag
var indexPaths = [IndexPath]()
button.setTitle(isExpanded ? "Open" : "Close", for: .normal)
if isExpanded {
tableView.deleteRows(at: indexPaths, with: .fade)
}else{
tableView.insertRows(at: indexPaths, with: .fade)
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !twodimensionalArray[section].isExpanded {
return 0
}
return twodimensionalArray[section].list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
return cell
}
}
答案 0 :(得分:1)
第1步
根据上次更新,在viewController中有一个标题数组
class YourViewController: UITableViewController { // as you marked the tableview delegate and datasource as override so your view controller should be subclass of UITableViewController
let btnTitles = [
"Open",
"Close",
"Action1",
...
]
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// although it's not quiet right creating button each time this section header view is prompted. You can cache these buttons with indexPath key, then try to get that button while the delegate asks for it, if not present than create it otherwise just reuse the returned button. But for this example it will work fine.
let button = UIButton(type: .system)
button.setTitle(btnTitles[section], for: .normal)
button.setTitleColor(.black, for: .normal)
button.backgroundColor = UIColor.lightGray
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
button.addTarget(self, action: #selector(handleExpandClose), for: .touchUpInside)
button.tag = section
return button
}
}
步骤2
这些设置将为您提供所需的内容。您没有共享numberOfRowsInSection
方法。哪个应该返回count
中的btnTitles
。
快乐的编码。