我正在尝试在应用中实现“收藏夹”按钮,这是我的尝试。这是我目前拥有的:
let favoriteButton: UIButton = {
let button = UIButton(type: .custom)
var emptyHeartImg = UIImage(named: "emptyheart")
var fullHeartImg = UIImage(named: "fullheart")
emptyHeartImg = emptyHeartImg?.maskWithColor(color: UIColor(r: 128, g: 171, b: 103))
fullHeartImg = fullHeartImg?.maskWithColor(color: UIColor(r: 128, g: 171, b: 103))
let imageView = UIImageView(image: emptyHeartImg, highlightedImage: fullHeartImg)
imageView.contentMode = .scaleAspectFill
button.setImage(imageView.image, for: .normal)
button.addTarget(self, action: #selector(handleFavorite), for: .touchUpInside)
return button
}()
@objc private func handleFavorite() {
if (favoriteButton.imageView?.isHighlighted)! == false {
favoriteButton.imageView?.isHighlighted = true
} else {
favoriteButton.imageView?.isHighlighted = false
}
}
当前,这并不能根据需要更改图像。有关实现“收藏夹”按钮的任何提示或替代方法?
答案 0 :(得分:0)
我将使用UIButton.isSelected
代替imageView的高亮状态。我不确定UIImageView
,但是isHighlighted
的按钮仅在它们被主动触摸时才出现,而不是在持久状态下。看到标有**的行:
let favoriteButton: UIButton = {
let button = UIButton(type: .custom)
var emptyHeartImg = UIImage(named: "emptyheart")
var fullHeartImg = UIImage(named: "fullheart")
emptyHeartImg = emptyHeartImg?.maskWithColor(color: UIColor(r: 128, g: 171, b: 103))
fullHeartImg = fullHeartImg?.maskWithColor(color: UIColor(r: 128, g: 171, b: 103))
**button.setImage(emptyHeartImg, for: .normal)
**button.setImage(fullHeartImg, for: .selected)
**button.imageView?.contentMode = .scaleAspectFill
button.addTarget(self, action: #selector(handleFavorite), for: .touchUpInside)
return button
}()
然后在您的处理程序中:
favoriteButton.isSelected = !favoriteButton.isSelected