arrays - 以编程方式在数组中设置按钮标题
问题描述
我有一组可扩展的按钮,它们都具有相同的标题“打开”。我希望每个按钮都有自己的名称,因为它们都有自己的功能。我将如何将每个按钮标题设置为独特的东西?我是否必须自己构建每个按钮并远离可扩展阵列?
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
}
}
解决方案
第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
of btnTitles
。
推荐阅读
- java - 执行jar文件时如何传递一长串JVM参数
- c++ - 反转纵横比时,OpenCV调整大小返回空图像
- mysql - 在 MySQL 的同一 UPDATE 语句中更新后使用原始列值
- python - 在多视图几何中最接近另一个 3D 点的线上查找 3D 点?
- java - groovy http-builder 模块现在在哪里?
- c++ - 格式化字符串输出上的 Eigen3 退出代码 127
- r - 按照特定模式更改多个变量名称
- python - 防止直接访问 Django 中的媒体文件
- angular - 如何有条件地为 ngx-datatable 的单元格着色
- conv-neural-network - CNN 只有 2 个 ConvLayer 时的批量归一化?