如何在函数名称中使用字符串

How to use a string in a function name

提问人:JOHNY 提问时间:8/16/2023 最后编辑:JOHNY 更新时间:8/16/2023 访问量:52

问:

我有这些功能:

private func chooseOfferButton1Tapped() {
        let vc = ChooseRdvVC()
        vc.offerCatched = arrayCatched![0]
        HapticsManager.shared.vibrate(for: .success)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func chooseOfferButton2Tapped() {
        let vc = ChooseRdvVC()
        vc.offerCatched = arrayCatched![1]
        HapticsManager.shared.vibrate(for: .success)
        navigationController?.pushViewController(vc, animated: true)
    }
                   ...

为止:

                   ...

private func chooseOfferButton50Tapped() {
        let vc = ChooseRdvVC()
        vc.offerCatched = arrayCatched![49]
        HapticsManager.shared.vibrate(for: .success)
        navigationController?.pushViewController(vc, animated: true)
    }

以下是我调用函数的方式:

let index = "chooseOfferButton\(oneViewSize)Tapped"
chooseOfferButton.addTarget(self,
                            action: Selector(index),
                            for: .touchUpInside)

其中是变化的数字oneViewSize

我正在寻找一种方法来避免仅在 2 个数字发生变化的情况下一遍又一遍地编写相同的函数。如何在函数名称中使用字符串?还是for循环?还是有其他方法?任何帮助都是值得赞赏的。

iOS Swift 函数 UIBubutton

评论


答:

0赞 Shabnam Siddiqui 8/16/2023 #1

如果您使用的是表视图,则需要在方法中使用 的属性tagUIButtoncellForRowAt indexPath

cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector(chooseOfferButtonTapped(_:)), for: .touchUpInside)
@objc func chooseOfferButtonTapped(_ sender:UIButton) {
    let vc = ChooseRdvVC()
    vc.offerCatched = arrayCatched[sender.tag]
    HapticsManager.shared.vibrate(for: .success)
    navigationController?.pushViewController(vc, animated: true)
}

或者,如果您正在使用,则需要为每个按钮设置标签,并为每个按钮设置相同的按钮单击操作@IBOutletCollection

 @IBOutlet var btnChooseOffer: [UIButton]!

 @IBAction func chooseOfferButtonTapped(_ sender: UIButton) {
  let vc = ChooseRdvVC()
    vc.offerCatched = arrayCatched[sender.tag]
    HapticsManager.shared.vibrate(for: .success)
    navigationController?.pushViewController(vc, animated: true)

}

评论

0赞 JOHNY 8/16/2023
我没有使用表格视图或情节提要,只是使用带有目标的常规按钮
0赞 Shabnam Siddiqui 8/16/2023
请参考此链接 - abhimuralidharan.medium.com/...
0赞 Shabnam Siddiqui 8/16/2023
了解如何重构按钮代码
1赞 vadian 8/16/2023 #2

正如其他人所提到的,只需要一个操作。索引通过按钮的属性传递。tag


与其将索引放入选择器中,不如将索引(又名)分配给oneViewSizetag

chooseOfferButton.addTarget(self,
                            action: #selector(chooseOfferButtonTapped),
                            for: .touchUpInside)
chooseOfferButton.tag = oneViewSize

在被调用方端,从按钮 (sender)

@objc private func chooseOfferButtonTapped(_ sender: UIButton) {
    let vc = ChooseRdvVC()
    let index = sender.tag
    vc.offerCatched = arrayCatched[index]
    HapticsManager.shared.vibrate(for: .success)
    navigationController?.pushViewController(vc, animated: true)
}

答:请声明非可选,因为您无论如何都会强制解开它arrayCatched