I am building an app using UIKit programmatically. I have a for loop to render 5 UIStackViews on the screen, every StackView has a click gesture that triggers a function.
private func configureCardsMainContainer() {
cardsMainContainer = UIStackView()
//...
for i in 0..<5 {
configureCardsHContainer(index: i)
}
//...
}
private func configureCardsHContainer(index:Int) {
cardsHContainer = UIStackView()
//...
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickView(_:)))
tapGesture.delegate = self
cardsHContainer.addGestureRecognizer(tapGesture)
}
@objc func clickView(_ sender: UIStackView) {
let details = DetailsViewController()
self.navigationController?.pushViewController(details, animated: true)
}
After clicking a clickable StackView it navigates to DetailsViewController, I want to set the navigation title of DetailsViewController to be something different for each StackView that has been clicked. The problem is, I cannot identify the sender view, is there any way to identify a sender which is a StackView?
CodePudding user response:
Simple, put your stacks into an array.
var stacks: [UIStackView] = []
private func configureCardsMainContainer() {
cardsMainContainer = UIStackView()
//...
stacks = 0..<5.map { createCardsHContainer(index: $0) }
//...
}
private func createCardsHContainer(index:Int) -> UIStackView {
let cardsHContainer = UIStackView()
//...
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickView(_:)))
tapGesture.delegate = self
cardsHContainer.addGestureRecognizer(tapGesture)
return cardsHContainer
}
@objc private func clickView(_ sender: UIStackView) {
guard let index = stacks.firstIndex(where: { $0 === sender }) else { return }
...
}
Of course, if you extract your repetitive component into a separate view, this can be done even simpler.