外观().setBackoundImage在自定义类上不起作用 [英] appearance().setBackgroundImage Not Working On Custom Class

查看:0
本文介绍了外观().setBackoundImage在自定义类上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已创建了一个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:

现在创建视图控制器并为事件barButton添加操作:

class ViewController: UIViewController {

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

并将此函数分配给BarButton:

用户界面输出:

这篇关于外观().setBackoundImage在自定义类上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆