我试图根据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)
答案 0 :(得分:0)
首先,您要向所有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
,并检查哪个帐户/ 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.
}