繁体   English   中英

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

[英]How to show one different image in a button toggle when tapped?

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

在按钮操作sortAction您需要将按钮设置为选定状态。 就像是:

sender.isSelected.toggle()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM