swift - 外观()。setBackgroundImage 不适用于自定义类
问题描述
我创建了一个 UIBarButtonItem 自定义类,并在情节提要中为该类分配了一个条形按钮项。
在应用程序委托中,我尝试使用以下方法为其设置外观:
VIPButton.appearance().setBackgroundImage(UIImage(named: "vipButton"), for: .normal, barMetrics: .default)
但是,虽然这适用于常规 UIBarButtonItems,但它对我的自定义类栏按钮项没有影响。
任何帮助,将不胜感激。
解决方案
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:
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:
UI output:
推荐阅读
- c# - 如何从图像opencv中去除小噪声(几个不规则的小形状)
- imagemagick - imagemagick 转换后的图像是灰色的
- machine-learning - 没有导数的梯度下降
- css - 在带有文本的元素周围添加边框
- css - 如何将此 CSS 代码仅应用于 Wordpress 上的一页?
- c++ - Linux 上的共享库和全局 std::string 问题
- ocaml - 如果两个输入列表是字谜,如何在 OCAML 中编写一个返回“true”的函数
- python - CSV 文件数据组织(结构化数据)
- java - 如果 HIbernate 使用 JDBC 本身,它究竟做了什么
- opengl-es - glDepthMask 似乎没有按预期工作?