2015-06-10 31 views

回答

1

這是我做到了斯威夫特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") 
} 
4

在運行期間,您不能更改UIBarButtonItem的樣式。您必須刪除UIBarButtonItem,然後添加您想要的UIBarButtonItem

@IBOutlet weak var toolBar: UIToolbar! 
var pauseButton = UIBarButtonItem() 
var playButton = UIBarButtonItem() 
var arrayOfButtons = [AnyObject]() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    pauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseButtonTapped") 
    playButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playButtonTapped") 

    arrayOfButtons = self.toolBar.items! 
    arrayOfButtons.insert(playButton, atIndex: 0) // change index to wherever you'd like the button 
    self.toolBar.setItems(arrayOfButtons, animated: false) 
} 

func playButtonTapped() { 
    arrayOfButtons = self.toolBar.items! 
    arrayOfButtons.removeAtIndex(0) // change index to correspond to where your button is 
    arrayOfButtons.insert(pauseButton, atIndex: 0) 
    self.toolBar.setItems(arrayOfButtons, animated: false) 
} 

func pauseButtonTapped() { 
    arrayOfButtons = self.toolBar.items! 
    arrayOfButtons.removeAtIndex(0) // change index to correspond to where your button is 
    arrayOfButtons.insert(playButton, atIndex: 0) 
    self.toolBar.setItems(arrayOfButtons, animated: false) 
} 

UIBarButtonItem Class Reference

0

我相信你已經找到了你的問題的解決方案,但我會在任何人的情況下仍然需要它離開這個。

UIBarButtonItem不是UIControl,但是你可以用自定義視圖初始化它,即自定義UIButton程序如下:

let playButton = UIButton(frame: CGRectMake(0, 0, 30, 30)) 
playButton.addTarget(self, action: "togglePlay:", forControlEvents: .TouchUpInside) 
playButton.setImage(UIImage(named: "play-active"), forState: .Normal) 
playButton.setImage(UIImage(named: "play-inactive"), forState: .Selected) 
let rightButton = UIBarButtonItem(customView: playButton) 
self.navigationItem.setRightBarButtonItems([rightButton], animated: true) 

想法來自Custom "Pressed" UIBarButtonItem Backgrounds

相關問題