Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Created December 6, 2018 07:02
Show Gist options
  • Save KentarouKanno/4d10ccdbef7c34e4c4a34c32413a62f4 to your computer and use it in GitHub Desktop.
Save KentarouKanno/4d10ccdbef7c34e4c4a34c32413a62f4 to your computer and use it in GitHub Desktop.

@IBInspectableを使用して背景色を変更するカスタムボタン

import UIKit

enum BackColorType: Int {
    case green = 1
    case blue = 2
    case yellow = 3
    
    var normalImageName: String {
        switch self {
        case .green: return "green_normal"
        case .blue: return "blue_normal"
        case .yellow: return "yellow_normal"
        }
    }
    
    var highLightedImageName: String {
        switch self {
        case .green: return "green_selected"
        case .blue: return "blue_selected"
        case .yellow: return "yellow_selected"
        }
    }
}

@IBDesignable
final class BackColorButton: UIButton {
    
    override var isHighlighted: Bool {
        willSet {
            super.isHighlighted = newValue
            self.titleEdgeInsets = newValue ? UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0) : .zero
        }
    }
    
    @IBInspectable
    private var backColor: Int = 0 {
        didSet {
            guard let buttonBackType = BackColorType(rawValue: backColor) else { return }
            let normalImage = UIImage(named: buttonBackType.normalImageName,
                                      in: Bundle(for: classForCoder),
                                      compatibleWith: traitCollection)
            self.setBackgroundImage(normalImage, for: .normal)
            
            let highLightedImage = UIImage(named: buttonBackType.highLightedImageName,
                                           in: Bundle(for: classForCoder),
                                           compatibleWith: traitCollection)
            self.setBackgroundImage(highLightedImage, for: .highlighted)
        }
    }
    
    // Public Method - Change Color
    var backColorType: BackColorType? = nil {
        didSet {
            if let backColorType = backColorType {
                backColor = backColorType.rawValue
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment