Изменить значок BarButtonItem при нажатии

Я пытаюсь создать счетчик. Идея довольно проста: вы нажимаете кнопку «воспроизведение», и после того, как вы нажмете, она должна исчезнуть и стать значком «пауза», который вызовет другое действие.

Я думал, что установка var для состояния счетчика и изменение значка (только с одной кнопкой) помогут, но я понятия не имею, как установить изображение кнопки для «паузы» или любого другого, которое появляется в раскрывающемся списке меню, когда вы создаете его из панели раскадровки.

Вот код:

@IBOutlet weak var playButton: UIBarButtonItem!
var timer = NSTimer()
var currentStatus = "stopped"


@IBAction func playAction(sender: AnyObject) {
    if (currentStatus == "stopped"){
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTimer"), userInfo: nil, repeats: true)
        currentStatus = "running"
        // change button icon (playButton) to Stop
    }
    else {
        currentStatus = "stopped"
        timer.invalidate()
       // change button icon (playButton) to Play
    }

}

person E Rodriguez    schedule 18.02.2016    source источник
comment
Можете ли вы опубликовать код выхода вашего элемента кнопки бара, если он у вас есть? Если у вас нет подключенной розетки, советую сделать ее.   -  person tktsubota    schedule 18.02.2016
comment
Да, он подключен, я отредактировал его, и теперь вы можете его увидеть (playButton var)   -  person E Rodriguez    schedule 18.02.2016
comment
Возможный дубликат Как изменить значок кнопки панели при нажатии в Swift?   -  person Pol    schedule 23.06.2018


Ответы (2)


Вы можете установить стиль кнопки следующим образом:

//setButton to play
yourBarButtonItem = UIBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
//setButton to stop
yourBarButtonItem = UIBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "TheMethodThatTheButtonShouldCall"), animated: true)
person Harshal Bhavsar    schedule 18.02.2016
comment
Я пропустил некоторые импорты? он говорит, что неразрешенный идентификатор 'BarButtonitem': S - person E Rodriguez; 18.02.2016
comment
Нет, @HarsalBhavsar. Я пробовал: UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: TheMethodThatTheButtonShouldCall), что, по-видимому, правильно и вообще не работает. На самом деле я начинаю думать, что это невозможно.. :/ - person E Rodriguez; 19.02.2016
comment
Можно скриншот вашего экрана? - person Harshal Bhavsar; 19.02.2016

Вы можете установить стиль кнопки с помощью массива следующим образом:

   func addCustomNavigationItemAtLeftAndRightSide(leftButtonItems:[UIBarButtonItem], rightButtonItems:[UIBarButtonItem]) {

    self.navigationItem.leftBarButtonItems = leftButtonItems
    self.navigationItem.rightBarButtonItems = rightButtonItems
 }

Вы можете использовать стиль следующим образом:

  let leftButtonItem = UIBarButtonItem(image: UIImage(named: "ic_top_back"), style: .Plain, target: self, action: "onBackButtonClicked:")
  addCustomNavigationItemAtLeftAndRightSide([leftButtonItem], rightButtonItems: [])
person Pheaktra Ty    schedule 19.02.2016