首页 > 解决方案 > 以编程方式在数组中设置按钮标题

问题描述

我有一组可扩展的按钮,它们都具有相同的标题“打开”。我希望每个按钮都有自己的名称,因为它们都有自己的功能。我将如何将每个按钮标题设置为独特的东西?我是否必须自己构建每个按钮并远离可扩展阵列?

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
}
}

我也会发布一张图片来描述。 在此处输入图像描述

标签: arraysswiftuitableviewbutton

解决方案


第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方法。哪个应该返回countof btnTitles


推荐阅读