外觀().setBackoundImage在自定義類上不起作用 [英] appearance().setBackgroundImage Not Working On Custom Class
本文介紹了外觀().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")
}
}
用戶界面輸出:
這篇關于外觀().setBackoundImage在自定義類上不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!
查看全文