ios - 在 iOS 中实现收藏夹按钮

标签 ios swift uibutton uiimageview

我正在尝试在应用程序中实现最喜欢的按钮,这是我的尝试。这是我目前拥有的:

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
    }
}

目前这并没有根据需要改变图像。有什么技巧或替代方法来实现收藏夹按钮吗?

最佳答案

我会使用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

关于ios - 在 iOS 中实现收藏夹按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137173/

相关文章:

ios - 如何在 Objective C 中从 uiwebview 保存 pdf

objective-c - 如何在 iOS 应用程序中使用自定义字体?

iOS - 将图像/容器 View 放置在导航栏上方

ios - 使用 Swift 进行应用内购买

ios - 通过单击不同的按钮启用禁用的按钮

ios - 为什么我的 project.pbxproj 文件会更改其格式

swift - Audiokit 修剪音频

swift - 在 Swift 的元组中是否可以有一个 nil 值?

ios - UIButton 随动画显示和消失

以png图像为背景的iOS5按钮透明度