我创建了一个自定义的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?
}

最佳答案

您可能想使用setImageUIButton属性,

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

09-10 07:02
查看更多