Как определить, какое подпредставление щелкнуло и установить для него действие в UIStackview? - PullRequest
0 голосов
/ 14 июня 2019

Я пытаюсь перейти к определенному экрану в зависимости от подпредставления, щелкнувшего в UIStackView. Как установить жест касания для представления и узнать, в каком подпредставлении я действительно нажал?

ViewModel.swift

    let currentAccount = UIAccountCardView(accountType: "Account 1",
                                           accountNumber: "",
                                           accountBalance: "")

    let savingsAccount = UIAccountCardView(accountType: "Account 2",
                                           accountNumber: "",
                                           accountBalance: "")

    let basicSavingsAccount = UIAccountCardView(accountType: "Account 3",
                                                accountNumber: "",
                                                accountBalance: "")

    let accounts = [currentAccount, savingsAccount, basicSavingsAccount]

    let accountCards = Observable.just(accounts)

ViewController.swift

viewModel.output.accountCards
            .subscribe(onNext: { accounts in
                accounts.forEach({ [weak self] cardView in
                    // Set tap gesture recognizer here?
                    // How do I know which cardView did I tap on?
                    self?.dashboardView.accountStackView.addArrangedSubview(cardView)
                })
            })
            .disposed(by: disposeBag)

1 Ответ

0 голосов
/ 14 июня 2019

Сначала вы захотите добавить распознаватель жестов касания ко всем cardViews.Добавьте это к вашему accounts.forEach:

// Make sure we're using strong reference to self.
guard let strongSelf = self else { return }
// Add arranged subview.
strongSelf.dashboardView.accountStackView.addArrangedSubview(cardView)
// Add tap recognizer.
let tap = UITapGestureRecognizer(target: strongSelf, action: #selector(strongSelf.accountWasSelected(_:))
cardView.addGestureRecognizer(tap)
// Not typically necessary, but just in case you could set:
cardView.isUserInteractionEnabled = true

Затем выполните действие func для селектора и проверьте, какой экземпляр account / cardView вызвал его.

@objc func accountWasSelected(_ account: UIAccountCardView) {
    if account == savingsAccount {
        // Do stuff with savings.
    } else if account == currentAccount {
        // Do stuff with current.
    } else if account == basicSavingsAccount {
        // Do stuff with basic
    }
    // etc.
}
...