首页 > 解决方案 > 外观()。setBackgroundImage 不适用于自定义类

问题描述

我创建了一个 UIBarButtonItem 自定义类,并在情节提要中为该类分配了一个条形按钮项。

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

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

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

任何帮助,将不胜感激。

标签: swiftuibarbuttonitem

解决方案


create custom class from 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)
        }
    }
}

Next you create a class from UIBarButtomItem. now set customView property to SimpleButon for custom Appearance and set action for this like below:

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)
    }
}

I created a class in this section and assigned a button to the customView variable.

Now I add style to SimpleButton like this:

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

now for create BarButtonItem on storyboard and change custom class to SimpleBarButton:

enter image description here

now create ViewController and add action for event barButton:

class ViewController: UIViewController {

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

and assign this function to BarButton: enter image description here

UI output:

enter image description here


推荐阅读