首页 > 解决方案 > 相同的类按钮在点击时的反应不同

问题描述

我想构建一个可扩展的按钮,例如选择器。点击该按钮将显示可供选择的选项。出于某种原因,选项按钮无法识别触摸。这是应用程序中广泛使用的主按钮。传递的动作在touchesEnded. 我做一些其他的事情,比如反馈和动画touchesBegan

class RoundButton: UIButton {

    private let action: (()->())

    init(action: @escaping ()->()) {
        self.action = action
        super.init(frame: .zero)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        action()
    }
}

具有的基本视图RoundButton和选项也是RoundButton

class ExpandableRoundButton: UIView {
    
    private var children: [RoundButton] = []
    private lazy var main: RoundButton = {
        RoundButton(action: { [ weak self] in
            self?.didTapMainButton()
        })
    }()

    init(children: [RoundButton]) {
        self.children = children
        super.init(frame: .zero)
    }

    private func didTapMainButton() {
        if children.first?.transform == .identity {
            expand()
        } else {
            collapse()
        }
    }
    
    func expand() {
        let spacing: CGFloat = 16
        children.enumerated().forEach { index, button in
            button.isHidden = false
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseIn]) {
                let translation = (button.frame.width + spacing) * CGFloat(index + 1)
                button.transform = CGAffineTransform(translationX: translation, y: 0)
            } completion: { _ in }
        }
    }
    
    func collapse() {
        children.enumerated().forEach { _, button in
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseIn]) {
                button.transform = .identity
            } completion: { _ in
                button.isHidden = true
            }
        }
    }
}

并执行上述基础视图。儿童按钮无法识别水龙头的问题。点击转到下一个响应者。不明白这是怎么可能的,因为子按钮和主按钮是相同的类型。


class SelectColorRoundButton: ExpandableRoundButton {
    
    init(action: @escaping (UIColor)->()) {
        
        let children: [RoundButton] = DrawingColor.allCases.map { color in
            let button = RoundButton(image: UIImage(), action: { action(color.color) })

            return button
        }
        super.init(children: children)
    }
}

标签: iosswiftuibuttonuikituigesturerecognizer

解决方案


推荐阅读