目前这段代码执行一个标记样式的列表,当我想尝试将addTarget操作选项传递给我的UIViewController时,问题仍然存在
抽屉视图.swift


let menuOptions = ["Info", "Actions", "Users", "Patiens"]

        menuOptions.forEach({

            let button = UIButton()
            button.setTitle($0, for: .normal)

            if $0.contains(menuOptions[0]) {
                button.style(with: .filled)
            } else {
                button.style(with: .outlined)
                button.addTarget(self, action: #selector(optionClicked(_:)), for: .touchUpInside)
            }
            actionStackView.addArrangedSubview(button)
        })

抽屉控制器.swift

class DrawerController: UIViewController {

    var shareView = DrawerView()
    var viewModel: CarDetailViewModel?

    override func loadView() {
        shareView.viewModel = viewModel
        view = shareView
    }

    @objc func optionClicked(_ sender: UIButton) {

        let feedbackGenerator = UISelectionFeedbackGenerator()
        feedbackGenerator.selectionChanged()

        let optionClicked: String = sender.titleLabel?.text ?? "0"

        switch optionClicked {
        case "Actions": present(DrawerActionController(), animated: true, completion: nil)
        case "Notifications":
            let viewController = DrawerNotificationController()
            viewController.carDetailViewModel = viewModel
           present(viewController, animated: true, completion: nil)

        case "Patients":
            let viewUserController = DrawerUserController()
            viewUserController.carPath = "9000"
           present(viewUserController, animated: true, completion: nil)
        default: break
        }
    }
}


已尝试按钮。addTarget(self,action:#选择器(optionClicked(#:)),for:.touchind)但未成功。

最佳答案

在方法button.addTarget(self, action: #selector(optionClicked(_:)), for: .touchUpInside)中,需要提供指向将接收操作的viewController的指针。
在您的例子中,最简单的方法是在init上创建带有drawer controller的惰性变量DrawerView,并在按钮操作中使用drawer控制器。
抽屉视图.swift

class DrawerView: UIView {

    private unowned let drawerController: DrawerController

    init(drawerController: DrawerController) {
        self.drawerController = drawerController
    }

    ... wherever is your code placed ...

    let menuOptions = ["Info", "Actions", "Users", "Patiens"]

    menuOptions.forEach({

        let button = UIButton()
        button.setTitle($0, for: .normal)

        if $0.contains(menuOptions[0]) {
            button.style(with: .filled)
        } else {
            button.style(with: .outlined)
            button.addTarget(drawerController, action: #selector(DrawerController.optionClicked(_:)), for: .touchUpInside)
            actionStackView.addArrangedSubview(button)
        }
    })

    ....
}

使用unownedweak来防止保留周期和内存泄漏很重要
要创建抽屉视图,可以使用惰性变量:
lazy var shareView: DrawerView = DrawerView(drawerController: self)

lazy将允许您使用self,您也可以使用optional并在稍后创建变量,但这基本上就是lazy所做的。
希望有帮助!

关于ios - 在UIViewController上执行的UIView上的动态创建UIButton AddTarget,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57859161/

10-10 20:41