【问题标题】:One button, 2 action and name change, Swift?一键,2个动作,改名,斯威夫特?
【发布时间】:2014-11-04 08:57:29
【问题描述】:

我是这个领域的新手,所以也许是一个非常简单的问题,我不知道,关于 swift。我知道如何制作 2 个用于秒表的按钮,启动和停止。但我想有相同的按钮来启动和停止秒表,然后文本从停止变为开始,这可能吗?如何?

【问题讨论】:

  • 我不确定这个问题是否真的与 Swift 有关。这是非常基本的 Cocoa / Foundation 的东西。你有开发 iOS / OSX 的经验吗?
  • 不,我刚开始 3 周前,在网上搜索过但没有运气,但也许我什至不知道如何正确搜索!
  • 我建议拿起一本书或寻找有关使用 Cocoa for iOS 或 OSX 编程的介绍性教程。要了解您的要求,要涵盖的内容太多,无法适应 stackoverflow 的答案。

标签: button swift action


【解决方案1】:

我能够创建一个满足您要求的简单 iOS 项目。这是一步一步的。

在项目的Storyboard 中创建一个UIViewController 场景并将其命名为“ViewController”。在场景中添加带有一些自动布局约束的UIButton。在您的项目导航器中,创建一个 UIViewController 子类文件,其中包含以下代码:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myButton: UIButton!

    var timer: NSTimer?
    var myInt = 0

    var launchBool: Bool = false {
        didSet {
            if launchBool == true {
                myButton.setTitle("Stop", forState: .Normal)
                timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "fireStopWatch", userInfo: nil, repeats: true)
            } else {
                myButton.setTitle("Start", forState: .Normal)
                timer?.invalidate()
                timer = nil
                myInt = 0
            }
        }
    }


    @IBAction func buttonAction(sender: AnyObject) {
        launchBool = !launchBool //true to false, false to true...
    }

    func fireStopWatch() {
        myInt += 1
        println(myInt)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        myButton.setTitle("Start", forState: .Normal)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

将您的@IBAction@IBOutlet 链接到您的ViewController 场景中的UIButton。启动您的项目。

每次点击UIButton,它的标题都会在“开始”和“停止”之间切换。每次单击“开始”时,它都会在 Xcode 控制台中显示不断增加的 myInt 值。每次单击“停止”时,它都会停止您的 NSTimer 并将 myInt 重置为 0。

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    相关资源
    最近更新 更多