如何在 UIKit 中识别可点击的堆栈视图?

How to identify a clickable Stack View in UIKit?

我正在以编程方式使用 UIKit 构建应用程序。 我有一个 for 循环来在屏幕上呈现 5 个 UIStackView,每个 StackView 都有一个触发功能的点击手势。

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

单击可单击的 StackView 后,它导航到 DetailsViewController,我想将 DetailsViewController 的导航标题设置为对于已单击的每个 StackView 不同的内容。 问题是,我无法识别发件人视图,有什么方法可以识别发件人是 StackView 吗?

很简单,把你的堆栈放到一个数组中。

var stacks: [UIStackView] = []

private func configureCardsMainContainer() {
   cardsMainContainer = UIStackView()
   //...

   stacks = 0..<5.map { createCardsHContainer(index: [=10=]) }

   //...
}

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: { [=10=] === sender }) else { return }

    ...
}

当然,如果您将重复的组件提取到单独的视图中,则可以做得更简单。