How to change the icon of a Bar Button when pressed in Swift?

前端 未结 3 1820
小鲜肉
小鲜肉 2021-02-10 16:23

I\'m creating a stopwatch in Swift and I want to change the play icon I have selected for a bar button to a pause icon when the button is pressed to start the stopwatch. How do

3条回答
  •  礼貌的吻别
    2021-02-10 17:03

    For Swift 3

    This is how I did it in Swift 3:

    var favoritesBarButtonOn: UIBarButtonItem!
    var favoritesBarButtonOFF: UIBarButtonItem!
    
    favoritesBarButtonOn = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOff"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOn))
    favoritesBarButtonOFF = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOn"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOFF))
    
    self.navigationItem.rightBarButtonItems = [self.rightNavBarButton, self.favoritesBarButtonOn]
    
    func didTapFavoritesBarButtonOn() {
        self.navigationItem.setRightBarButtonItems([self.rightNavBarButton, self.favoritesBarButtonOFF], animated: false)
        print("Show Favorites")
    }
    
    func didTapFavoritesBarButtonOFF() {
        self.navigationItem.setRightBarButtonItems([self.rightNavBarButton, self.favoritesBarButtonOn], animated: false)
        print("Show All Chat Rooms")
    }
    

    For Swift 4

    var favoritesBarButtonOn: UIBarButtonItem! var favoritesBarButtonOFF: UIBarButtonItem!

    favoritesBarButtonOn = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOff"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOn))
    favoritesBarButtonOFF = UIBarButtonItem(image: #imageLiteral(resourceName: "TabBarIconSettingsOn"), style: .plain, target: self, action: #selector(didTapFavoritesBarButtonOFF))
    
    self.navigationItem.rightBarButtonItems = [self.favoritesBarButtonOn]
    
    func didTapFavoritesBarButtonOn() {
        self.navigationItem.setRightBarButtonItems([self.favoritesBarButtonOFF], animated: false)
        print("Show Favorites")
    }
    
    func didTapFavoritesBarButtonOFF() {
        self.navigationItem.setRightBarButtonItems([self.favoritesBarButtonOn], animated: false)
        print("Show All Chat Rooms")
    }
    

提交回复
热议问题