如何在我的自定义开关切换上触发事件

how to fire an event on my custom switch toggle

我正在创建自定义开关,但我不知道如何创建每次用户切换开关时都会触发的自定义事件

我知道它与 UIControl 有关,但我对此一无所知。

这是我的 class

@IBDesignable
public class CustomSwitch: UIView {

    enum MyCustomEvents: UInt{
        case valueChanged
    }

    @IBInspectable public var isOn: Bool = true
    @IBInspectable public var OffColor: UIColor! = .white
    @IBInspectable public var onColor: UIColor! = .green

    public let valueChanged: UIControl = UIControl()

    private var ball: UIView = UIView()
    private var ballwidth: CGFloat!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSwitch()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupSwitch()
    }

    private func setupSwitch() {

        if isOn {
            backgroundColor = onColor
        }else {
            backgroundColor = OffColor
        }

        self.layer.cornerRadius = height/2
        setupBall()

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)

    }

    private func setupBall() {
        ballwidth = height-2
        ball.frame = .init(x: 1, y: 1, width: ballwidth, height: ballwidth)
        ball.layer.cornerRadius = ballwidth/2
        ball.backgroundColor = .white

        if isOn {
            self.ball.frame.origin.x = self.width - self.ballwidth - 1
        }else {
            self.ball.frame.origin.x = 1
        }

        self.addSubview(ball)
    }

    public func toggle(_ animated: Bool) {

        isOn = !isOn

        if animated {
            UIView.animate(withDuration: 0.3) {
                if self.isOn {
                    self.ball.frame.origin.x = self.width - self.ballwidth - 1
                    self.backgroundColor = self.onColor
                }else {
                    self.ball.frame.origin.x = 1
                    self.backgroundColor = self.OffColor
                }
            }
        }else{
            if isOn {
                ball.frame.origin.x = width - ballwidth - 1
                backgroundColor = onColor
            }else {
                ball.frame.origin.x = 1
                backgroundColor = OffColor
            }
        }

    }

    @objc private func tapped(_ gesture: UIGestureRecognizer) {
        toggle(true)
    }


}

请帮忙!

您可以将您的基础从 UIView 更改为 UIControl,然后在您的切换功能中添加一个值更改操作

public class CustomSwitch: UIControl {
...
...
    public func toggle(_ animated: Bool) {
    isOn = !isOn
    sendActions(for: UIControl.Event.valueChanged)
    ...
    }

然后您可以添加您需要的目标

customSwitchTest.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)