Установить заголовки кнопок программно в массиве - PullRequest
0 голосов
/ 22 октября 2018

У меня есть массив расширяемых кнопок с одинаковым названием «Открыть».Я бы хотел, чтобы у каждой кнопки было свое имя, поскольку все они будут иметь свои особенности.Как мне настроить каждый заголовок кнопки на что-то уникальное?Должен ли я создать каждую кнопку самостоятельно и отойти от расширяемого массива?

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

Я также выложу картинку для описания.enter image description here

1 Ответ

0 голосов
/ 23 октября 2018

Шаг # 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.

Счастливое кодирование.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...