使用枚举的自定义UIButton类配置不适用于#selector和@objc

时间:2019-07-07 20:23:53

标签: swift uikit

我正在尝试访问自定义UIButton类的枚举参数,但无法使其在#selector和@objc代码之间起作用。有任何想法吗?

这样做的目的是基于交互,我拥有不同样式的按钮,这些按钮对用户而言看起来有所不同。我可以使用已设置的枚举来格式化等。但是我无法弄清楚如何将ButtonStyle枚举参数放入代码的@objc部分。

我通过调用以下方法在viewController中实例化自定义按钮类的实例:

let button = ColorButton(title: "A Button", style: .action)

自定义类的代码如下:

import UIKit

enum ButtonStyle {
    case action
    case optional
}


var buttonStyleToUse = ButtonStyle.action


class ColorButton: UIButton {

    // MARK: GESTURE RESPONDERS

    @objc fileprivate func touchDownOnButton()
    {
        updateButtonColors(forStyle: buttonStyleToUse)
    }

    @objc fileprivate func touchOnButtonCancelled()
    {
        setUpButtonColors(forStyle: buttonStyleToUse)
    }


    // MARK: INIT

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

    }


    init(title: String, style: ButtonStyle) {

        super.init(frame: .zero)

        // Set button title parameters
        setTitle(title, for: .normal)
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17.0)

        // Set button later parameters
        layer.cornerRadius = 10
        layer.masksToBounds = true

        // Set button height
        height(50)

        // Update class variable to sender
        buttonStyleToUse = style

        // Perform initial button setup based on button style
        setUpButtonColors(forStyle: buttonStyleToUse)

        // Add interaction targets
        addTarget(self, action: #selector(touchDownOnButton), for: .touchDown)
        addTarget(self, action: #selector(touchDownOnButton), for: .touchDragEnter)
        addTarget(self, action: #selector(touchOnButtonCancelled), for: .touchDragExit)

    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    // MARK: METHODS

    func setUpButtonColors(forStyle: ButtonStyle){

        switch forStyle {
        case .action:
            setTitleColor(.white, for: .normal)

            // Set button background colors
            backgroundColor = actionButtonColor

        default: //Optional and others
            setTitleColor(.black, for: .normal)

            // Set button background colors
            backgroundColor = optionalButtonColor

        }

    }

    func updateButtonColors(forStyle: ButtonStyle){

        switch forStyle {
        case .action:
            setTitleColor(.white, for: .normal)

            // Set button background colors
            backgroundColor = tappedActionButtonColor

        default: //Optional and others
            setTitleColor(.black, for: .normal)

            // Set button background colors
            backgroundColor = tappedOptionalButtonColor

        }

    }

}

0 个答案:

没有答案