如何动态更改自定义UIButton的图像



我创建了一个自定义UIButton类,使其看起来像下拉选择。我在按钮的右边有一个向下的小箭头图像。我想根据不同的条件将按钮的图像更改为不同的图像,如灰色、白色或红色。怎么做?以下是我的代码:

class DropDownButton: UIButton {
let dropDownImageGrey = UIImage(named: "Icons/DropDown/Grey")
let dropDownImageWhite = UIImage(named: "Icons/DropDown/White")
let dropDownImageRed = UIImage(named: "Icons/DropDown/Red")
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: self.frame.width - 108, bottom: 0, right:0)
self.setImage(dropDownImageGrey, for: [])
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -13, bottom: 0, right:0)
}
}
override func viewDidLoad() {
// Change image to red one
dropDownButton.??? // How to change?
}

您可能需要使用UIButtonsetImage属性,

override func viewDidLoad() {
// Change image to red one
let dropDownButton = DropDownButton()
dropDownButton.setImage(dropDownButton.dropDownImageRed, for: .normal)
}

如果图像添加在Assets.xcassets中,则可以使用image literals或直接使用等名称

let dropDownImageGrey = UIImage(named: "Grey")
let dropDownImageWhite = UIImage(named: "White")
let dropDownImageRed = UIImage(named: "Red")

我认为上面的一些答案是有效的。然而,为了生成代码,我建议使用enum作为图像列表。

class DropDownButton: UIButton {
enum ImageType: String {
case grey = "Icons/DropDown/Grey"
case white = "Icons/DropDown/White"
case red = "Icons/DropDown/Red"
var image: UIImage? { return UIImage(named: rawValue) }
}
var imageType: ImageType = .red {
didSet {
setImage(imageType.image, for: .normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: self.frame.width - 108, bottom: 0, right:0)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -13, bottom: 0, right:0)
}
}
override func viewDidLoad() {
// Change image to red one
dropDownButton.imageType = .red
}

稍后,如果需要更改图像类型,只需设置按钮的imageType即可。像

dropDownButton.imageType = .grey
dropDownButton.imageType = .white

您可以使用枚举来定义各种条件,并添加获取图像的方法。根据条件,您可以设置图像。示例如下:

在类之外定义此枚举

enum DropdownCondition
{
case condition1
case condition2
case condition3
func getImage() -> UIImage? {
switch self {
case .condition1:
return UIImage(named: "Icons/DropDown/Grey")
case .condition1:
return UIImage(named: "Icons/DropDown/White")
case .condition1:
return UIImage(named: "Icons/DropDown/Red")
default:
return nil
}
}
}

在您的视图中,DidLoad/init或任何基于条件调用MethodWithSomoCdition(.codition1(的方法。

override func viewDidLoad() {
// Change image to red one
let dropDownButton = DropDownButton()
//Call based on your condition
yourMethodWithSomeoCndition(.condition1)//This condition can change on the fly
}

func yourMethodWithSomeoCndition(_ condition:DropdownCondition)
{
self.dropDownButton.setImage(condition.getImage(), for: .normal)
}

最新更新