【问题标题】:How to show one different image in a button toggle when tapped?点击时如何在按钮切换中显示一个不同的图像?
【发布时间】:2019-08-19 02:40:42
【问题描述】:

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

【问题讨论】:

    标签: swift image button


    【解决方案1】:

    在您的按钮操作sortAction 中,您需要将您的按钮设置为选中状态。比如:

    sender.isSelected.toggle()
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2011-03-06
        • 2011-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多