Appearance().setBackgroundImage 不适用于自定义类

问题描述

我创建了一个 UIBarButtonItem 自定义类,并在故事板中为这个类分配了一个栏按钮项。

在应用程序委托中,我尝试使用以下方法为其设置外观:

VIPButton.appearance().setBackgroundImage(UIImage(named: "vipButton"),for: .normal,barMetrics: .default)

然而,虽然这适用于常规 UIBarButtonItems,但它对我的自定义类栏按钮项没有影响。

任何帮助将不胜感激。

解决方法

从 UIButton 创建自定义类:

public class SimpleButton: UIButton {

    @objc dynamic var backColor: UIColor? {
        didSet {
            self.backgroundColor = self.backColor
        }
    }
    
    @objc dynamic var image: UIImage? {
        didSet {
            self.setImage(self.image,for: .normal)
        }
    }
}

接下来从 UIBarButtomItem 创建一个类。 现在将 customView 属性设置为 SimpleButon 以自定义外观并为此设置操作,如下所示:

public class SimpleBarButton: UIBarButtonItem {
    
    // create object from simpleButton
    private let button = SimpleButton()
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
                
        // add target for button
        self.button.addTarget(self,action: #selector(self.buttonTapped(_:)),for: .touchUpInside)
        
        // set title
        self.button.setTitle("title",for: .normal)
        self.button.sizeToFit()
        
        // assing simple button to customView property
        self.customView = self.button
    }
    
    // get callback from touchUp button
    @objc func buttonTapped(_ sender: UIButton) {
        
        // here set callback for tapped on BarButtonItem
        // check target and action is not Nil
        guard let target = self.target,let action = self.action else {
            return
        }
        
        // call selector (implement to your ViewController)
        // pass self for parameters
        target.performSelector(inBackground: action,with: self)
    }
}

我在本节中创建了一个类,并为 customView 变量分配了一个按钮。

现在我像这样为 SimpleButton 添加样式:

SimpleButton.appearance().backColor = .red
SimpleButton.appearance().image = UIImage.init(named: "images")!

现在在情节提要上创建 BarButtonItem 并将自定义类更改为 SimpleBarButton:

enter image description here

现在创建 ViewController 并为事件 barButton 添加动作:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func sampleClicked(_ sender: SimpleBarButton) {
        print("callBack from action on BarButton Item")
    }
}

并将此功能分配给 BarButton: enter image description here

界面输出:

enter image description here