2015-04-15 3 views
1

Я пытаюсь переключить свою кнопку между воспроизведением и воспроизведением изображения при запуске и остановить тикер с помощью Swift. Мой код:Toggle Play/Pause UIBarButtonItem на панели инструментов с помощью Swift

import UIKit 

class ViewController: UIViewController { 

@IBOutlet var btnPlayPause: UIBarButtonItem! 
var isPlaying = false 
var timer = NSTimer() 
var count = 0 
@IBOutlet weak var lblTime: UILabel! 
@IBOutlet var myToolbar: UIToolbar! 




@IBAction func btnPlay(sender: UIBarButtonItem) 
    { 
    //set the button to animate 

    self.myToolbar.setItems([self.btnPlayPause], animated: true) 



    if !isPlaying //if the ticker is not ticking 
    { 
     //change the button to a pause button 


     println("worked")//start the ticker 

     timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true) 

     isPlaying = true 

    }else{ //if the ticker is ticking 

     //change the pause button to a play button 

     self.btnPlayPause = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: nil) 

     //pause the ticker 
     timer.invalidate() 
     //btnPlayPause.enabled = true 
     isPlaying = false 
     } 

} 

    @IBAction func btnReset(sender: UIBarButtonItem) 
{ 
    //reset and restart the ticker 
    timer.invalidate() 
    count = 0 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true) 

} 


@IBAction func btnStopit(sender: UIBarButtonItem) 
{ 
    //stop and reset the ticker to "0" 

    timer.invalidate() 
    count = 0 
    lblTime.text = String(count) 

    isPlaying = false 

} 

func updateTime() 
{ 
    //displays ticker label with count 

    lblTime.text = String(count++) 

} 

override func viewDidLoad() 
{ 

    super.viewDidLoad() 
    let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "btnStopit:") 
    self.btnPlayPause = button 
} 



override func didReceiveMemoryWarning() 
{ 

    super.didReceiveMemoryWarning() 

} 


} 

Слушать и все остальные кнопки на панели инструментов расчищают и панель инструментов создает кнопку паузы одна сама по себе, как это:

Initial ViewAfter btnPlayPause clicked

Я хочу просто переключите мою кнопку воспроизведения с помощью кнопки «Пауза», не удаляя ни одну из других кнопок с панели инструментов. Это возможно?

Если бы кто-нибудь мог мне помочь, я бы очень признателен!

Благодаря

+0

изменить, если isPlaying == ложь {...}, чтобы если! IsPlaying {...} –

+0

Я ценю предложение. Однако все, что делает, делает то же самое, что написано иначе. Я изменил его, как вы предложили, и это никак не влияет на конечный результат. – Unconquered82

+1

Если бы это решило вашу проблему, я бы опубликовал ее как ответ. Это просто правильный синтаксис для тестирования условия Bool –

ответ

4

Casting свою кнопку на новый экземпляр UIBarButtonItem не собирается делать необходимое. Сначала создайте розетку для вашей панели инструментов и извлеките существующие элементы, затем измените элемент кнопки воспроизведения в соответствии с ее положением на панели инструментов.

В моем случае кнопка переключения находится слева, поэтому я обращаюсь к ней с индексом 0 и заменяю ее соответствующим переключателем. И затем вызов setItems() на панели инструментов обновит вашу панель инструментов. Установите анимацию в true для красивой анимации с небольшим затуханием.

@IBOutlet weak var toolBar: UIToolbar! 

@IBAction func playPauseToggle(sender: UIBarButtonItem) { 

    var toggleBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playPauseToggle:") 

    if playing { 
     player.pause() 
     playing = false 
    } else { 
     player.play() 
     toggleBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "playPauseToggle:") 
     playing = true 
    } 

    var items = toolBar.items! 
    items[0] = toggleBtn 
    toolBar.setItems(items, animated: true) 

} 
1

чуть более плотная версия:

@IBAction func playPauseToggle(sender: UIBarButtonItem) { 
    var barButtonItems = toolBar.items! 
    barButtonItems[0] = UIBarButtonItem(barButtonSystemItem: player.rate == 1.0 ? .Pause : .Play, 
    target: self, action: "playPauseButtonWasPressed:") 
    toolBar.setItems(barButtonItems, animated: true) 
} 
1

// Этот код протестирован и работает с Swift 2

@IBOutlet слабый вар Панель навигации: UINavigationBar!

//playToPause() 
@IBAction func playButton(sender: UIBarButtonItem) { 

    let newBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "pauseButton:") 
    navigationBar.topItem?.rightBarButtonItem = newBarButton 
} 

// pauseToPlay() 
@IBAction func pauseButton(sender: UIBarButtonItem){ 

    let pauseBtnItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "playButton:") 
    navigationBar.topItem!.rightBarButtonItem = pauseBtnItem 
} 
Смежные вопросы