Unc*_*d82 1 toolbar toggle uibarbuttonitem swift
我正在尝试在播放和暂停图像之间切换我的按钮,当我开始并使用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()
}
}
Run Code Online (Sandbox Code Playgroud)
Play和工具栏上的所有其他按钮都清除,工具栏单独创建Pause按钮,如下所示:

我想只使用"暂停"按钮切换"播放"按钮,而不从工具栏中删除任何其他按钮.这可能吗?
如果有人能帮助我,我会非常感激!
谢谢
小智 5
将按钮转换为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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3273 次 |
| 最近记录: |