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

问题描述 投票:0回答:1

我有这些功能:

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

我正在寻找一种方法来避免只在 2 个数字发生变化的情况下一遍又一遍地编写相同的函数。如何在函数名称中使用字符串?还是for循环?或者还有别的办法吗?如有任何帮助,我们将不胜感激。

我使用按钮和目标选择器来调用函数,因此我无法传递任何参数。

ios swift xcode function uibutton
1个回答
0
投票

您需要一个行动

private func chooseOfferButtonTapped(_ offerCatched:String) {
    let vc = ChooseRdvVC()
    vc.offerCatched = offerCatched
    HapticsManager.shared.vibrate(for: .success)
    navigationController?.pushViewController(vc, animated: true)
}

如果

chooseOfferButtonTapped
是按钮的操作,则执行此操作

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

其中

sender.tag
是点击按钮对应的数字

© www.soinside.com 2019 - 2024. All rights reserved.