点击时如何在按钮切换中显示一个不同的图像?

时间:2019-03-28 10:48:12

标签: swift image button

我在UIViewController扩展的函数中设置了Button。我将两个图像设置为两个不同的状态。但这在按下按钮时不会改变。我该如何解决?

我尝试了此处提供的所有解决方案。

import Foundation
import UIKit

extension UIViewController {

    func addSortAndWeatherButton(sortAction: Selector, weatherAction: Selector){

    let sortButton: UIButton = UIButton(type: UIButton.ButtonType.custom)

    sortButton.setImage(UIImage(named: "sort-near.png"), for: .normal)
    sortButton.setImage(UIImage(named: "sort-rating.png"), for: .selected)

    sortButton.addTarget(self, action: sortAction, for: .touchUpInside)
    sortButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
    let sortBarButton = UIBarButtonItem(customView: sortButton)

    self.navigationItem.rightBarButtonItems = sortBarButton
    }

2 个答案:

答案 0 :(得分:0)

在按钮操作sortAction中,您需要将按钮设置为选定状态。像这样:

sender.isSelected.toggle()

答案 1 :(得分:0)

我遇到了同样的问题,我想根据状态更改“收藏夹”按钮图标。我的解决方案创建了两个不同的按钮。根据状态,更改custom view中的代码UIBarButtonItem

var isFavoriteButtonFilled = false

lazy var favoriteButton: UIButton = {
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    button.setBackgroundImage(UIImage(named: "navHeart"), for: .normal)
    button.addTarget(self, action: #selector(favoriteUser), for: .touchUpInside)
    return button
}()

lazy var filledFavoriteButton: UIButton = {
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    button.setBackgroundImage(UIImage(named: "navHeartFilled"), for: .normal)
    button.addTarget(self, action: #selector(favoriteUser), for: .touchUpInside)
    return button
}()

@objc private func favoriteUser() {

    let favoriteItem: UIBarButtonItem

    if isFavoriteButtonFilled {
        favoriteItem = UIBarButtonItem(customView: favoriteButton)
    } else {
        favoriteItem = UIBarButtonItem(customView: filledFavoriteButton)
    }

    isFavoriteButtonFilled.toggle()
    navigationItem.rightBarButtonItems = [favoriteItem]
}