Как использовать кнопку одного табличного представления, чтобы автоматически выбрать кнопку другого табличного представления все - PullRequest
1 голос
/ 01 мая 2020

Я делаю табличное представление, которое позволяет пользователям выбирать элементы, основной элемент является основным, а каждый основной элемент содержит вторичный список, я создал собственную ячейку, а также вставил другой табличный вид внутрь, как показано в ссылке на изображение ниже.

Форма изображения

Вот мой ViewController.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PrimaryDelegate {
@IBOutlet weak var tableView: UITableView!

    //This is my data
    var cardList = Card(userName: "Kevin", primaryList: [Card.Primary(primaryName: "Card1", secondaryList: [Card.Primary.Secondary(secondaryName: "Card1-1")]),Card.Primary(primaryName: "Card2", secondaryList: [Card.Primary.Secondary(secondaryName: "Card2-1"),Card.Primary.Secondary(secondaryName: "Card2-2")])])

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()

    }

@IBAction func enterAction(_ sender: Any) {
         //I hope here can print the result
         //How should I get the result from primaryList and secondaryList in Custom Cell ?
         print(cardList)
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cardList.primaryList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
        cell.primaryLabel.text = cardList.primaryList[indexPath.row].primaryName
        cell.secondaryList = cardList.primaryList[indexPath.row].secondaryList
        cell.primaryIndex = indexPath.row
        cell.primaryDelegate = self
        return cell
    }

    func primaryIndex(index:Int) {
        //I use delegate to get index, but how to tell which secondaryList needs to be selected all?
        print("primaryIndex\(index)")
    }

}

Вот моя пользовательская ячейка, она включает в себя другой вид таблицы, поэтому я чувствую сложно.

class CustomTableViewCell: UITableViewCell,UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var primaryBtn: UIButton!
    @IBOutlet weak var secondaryBtn: UIButton!
    @IBOutlet weak var primaryLabel: UILabel!
    @IBOutlet weak var secondaryLabel: UILabel!
    @IBOutlet weak var secondaryTableView: UITableView!
    @IBOutlet weak var secondaryHeight: NSLayoutConstraint!
    var primaryIndex:Int?
    var primaryDelegate:PrimaryDelegate?

    var secondaryList:[Card.Primary.Secondary]!{

        didSet{
            secondaryTableView.delegate = self
            secondaryTableView.dataSource = self
            secondaryTableView.reloadData()
            secondaryHeight.constant = secondaryTableView.contentSize.height
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return secondaryList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
        cell.secondaryLabel.text = secondaryList[indexPath.row].secondaryName
        return cell
    }

    @IBAction func primaryBtnAction(_ sender: UIButton) {
        sender.isSelected = !primaryBtn.isSelected
        primaryDelegate?.primaryIndex(index: primaryIndex!)
    }

    @IBAction func secondaryBtnAction(_ sender: UIButton) {
        sender.isSelected = !secondaryBtn.isSelected

    }

    override func awakeFromNib() {
        super.awakeFromNib()

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }

}

Я надеюсь, что это может быть ...

1. Когда пользователь выбирает основной элемент, он может автоматически помочь мне выбрать все дополнительные элементы. Однако первичный элемент может быть выбран только «один», и когда пользователь выбирает следующий первичный элемент, предыдущий элемент должен быть отменен, включая все вторичные элементы.

2. Когда пользователь нажимает enterAction, он Можно распечатать данные, которые выбрал пользователь. Мне нужно знать, что, если пользователь не выберет основной, Сколько выбран элемент вторичного списка. Я имею в виду, что результатом являются Card1-1 и Card2-1, они выбирают только элемент из вторичного списка.

Как мне указать табличному представлению пользовательской ячейки выбрать все, когда я выбираю основной элемент, и как пользовательская ячейка узнала, какая Основной выбран и нуждается в перезагрузке данных?

Если вам нужна дополнительная информация, пожалуйста, дайте мне знать, это правило выбора меня очень смущает. Спасибо

1 Ответ

1 голос
/ 01 мая 2020

Вы можете использовать это на вашем primaryBtnAction:

if sender.isSelected{
    for section in 0..<tableView.numberOfSections {
        for row in 0..<tableView.numberOfRows(inSection: section) {
            tableView.selectRow(at: IndexPath(row: row, section: section), animated: false, scrollPosition: .none)
        }
    }
} else { //Deselect statement
    tableView.deselectRow(at: IndexPath(row: row, section: section), animated: false)
}

Надеюсь, это поможет ...

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