我正在通过构建一个基本的计数应用程序(基于本教程 https://www.youtube.com/watch?v=3blma4PCRak(来学习 swift,并且我正在尝试拥有一个基于开关状态以 3 为增量计数的函数。
似乎我在网上和 SO 的教程中找到的很多答案都是多年前的,很多语法都被弃用了,包括:
•而不是现在oddSwitch.On
它是oddSwitch.isOn
• 说明颜色从UIColor.redColor
变为仅UIColor.red
等等...以下是我到目前为止的代码:
//
// ViewController.swift
// TestApp
//
// Created by kawnah on 2/8/17.
// Copyright © 2017 kawnah. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var outputLabel: UILabel? = UILabel();
var currentCount = 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.
}
@IBAction func addOneBUtton(_ sender: UIButton) {
currentCount = currentCount + 1
if currentCount <= 1 {
outputLabel?.text = "(currentCount) click"
} else {
outputLabel?.text = "(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
@IBOutlet var oddSwitch: UISwitch!
@IBAction func oddToggle(_ sender: UISwitch) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
}
}
}
我对@IBOutlet
和我的函数之间的关系感到困惑,该函数以 3 为增量进行计数。我也尝试过包括弱存储,但据我了解,这是@IBOutlet
的默认设置。目前,当我打开开关时,计数器仍然递增 1。
我的错误日志仅显示初始屏幕的 PNG 压缩错误,与代码无关。到底发生了什么?
更改您的 addOneBUtton 代码以匹配此代码。
@IBAction func addOneBUtton(_ sender: UIButton) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
} else {
currentCount = currentCount + 1
}
if currentCount <= 1 {
outputLabel?.text = "(currentCount) click"
} else {
outputLabel?.text = "(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
您可以删除此部分。
@IBAction func oddToggle(_ sender: UISwitch) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
}
}
所以完整的代码应该看起来像这样。
import UIKit
class testViewController: UIViewController {
//MARK: IBOutlets
@IBOutlet var outputLabel: UILabel? = UILabel();
@IBOutlet var oddSwitch: UISwitch!
//MARK: Vars
var currentCount = 0;
//MARK: Lifecyle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: IBActions
@IBAction func addOneBUtton(_ sender: UIButton) {
if oddSwitch!.isOn {
currentCount = currentCount + 3
} else {
currentCount = currentCount + 1
}
if currentCount <= 1 {
outputLabel?.text = "(currentCount) click"
} else {
outputLabel?.text = "(currentCount) clicks"
}
outputLabel?.textColor = UIColor.red
}
}
注意:这是我保持代码干净的转折,IBOutlets
全部集中在一个地方,并使用//MARK:
更快地跳转到代码部分。