【问题标题】:Have changeable button in Swift在 Swift 中有可更改的按钮
【发布时间】:2015-10-18 10:12:50
【问题描述】:

我目前正在学习 Swift 和 iOS 编程。我学会了创建一个显示秒表的秒表应用程序。我目前正在尝试将秒表的开始和停止按钮结合起来。这意味着当应用程序加载时,它会有一个开始按钮,但是当我按下开始按钮时,它会变成一个停止按钮,当我按下计时器停止并且按钮变为开始按钮时。我已经搜索了互联网和堆栈溢出,但我无法找到与我想要的类似的东西。我当前的代码附在下面!

import UIKit

class ViewController: UIViewController {

var timer = NSTimer()

var count = 0.0

func updateTime() {

    count = count + 0.1

    label.text = "\(count)"

}

@IBOutlet weak var label: UILabel!

@IBAction func start(sender: AnyObject) {

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


    }

@IBAction func pause(sender: AnyObject) {

    timer.invalidate()

}


@IBAction func reset(sender: AnyObject) {

    timer.invalidate()

    count = 0

    label.text = "0"

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.




}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

【问题讨论】:

  • 您在按钮上使用任何图像还是仅使用文本?
  • 哇!那很快。我正在使用一种叫做条形按钮项的东西
  • 您是否在使用导航栏或工具栏内的栏按钮项?这实际上很重要,因为答案比使用标准按钮稍微复杂一些(但仍然没有什么复杂的)。

标签: ios swift button timer stopwatch


【解决方案1】:

删除所有 IBActions 并执行此操作,仅删除操作是不够的,您需要右键单击按钮并断开所有 @IBactions 以删除完整的引用,否则会出错..

// 不要做这个@IBAction 这只是一个普通函数

 func start() {
>     timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: ("updateTime"), userInfo: nil, repeats: true)
> 
> 
>     } // smae here... just a function   
     func updateTime() {
> 
>     count = count + 0.1
> 
>     label.text = "\(count)"
> 
> } // same with this just a function 
>        func reset() {
> 
>     timer.invalidate()
> 
>     count = 0
> 
>     label.text = "0"
> 
> }  
> 
> // Now Make a @IBAction to your button , and sender should be UIButton
> 
>

     @IBAction func buttonPressed(sender : UIButton) {   
     if sender.currentTitle == "start" {
    >       sender.setTitle("stop", forState: UIControlState.Normal)
    >       reset() // perform any function that you want to when button is acting as stop button    } 
    else {
    >        sender.setTitle("start", forState: UIControlState.Normal)
    >        start() // perform any function that you want to when button is acting as start button 
    >      } }

【讨论】:

  • 我想@justinxfan 也想在印刷机上切换图像。因此,您需要创建另一个指向情节提要上的按钮的链接,这次是 IBOutlet 说名为 myButton 并在您想要切换图像时添加类似 self.myButton.setImage(UIImage(named: "StartButton.png") as UIImage!, forState: .Normal) 的内容。
  • 你不需要创建 @IBOutlet ,你可以在没有 sender.setImage(UIImage(named: "StartButton.png") , forState: .Normal) 的情况下做到这一点
  • 但是这段代码应该在@IBaction buttonpressed(sender : UIButton)里面
  • 你说得对,我没有注意到你有一个 UIButton 的发件人!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 2023-03-19
  • 2021-03-25
  • 2015-10-01
  • 1970-01-01
  • 2015-04-26
相关资源
最近更新 更多