gpt4 book ai didi

ios - 将开关状态绑定(bind)到 Swift 中的函数

转载 作者:行者123 更新时间:2023-11-28 15:52:40 25 4
gpt4 key购买 nike

我正在通过构建一个基本的计数应用程序(基于本教程 https://www.youtube.com/watch?v=3blma4PCRak)来快速学习,并且我正在尝试拥有一个基于开关状态以 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 和我声明以三为增量计数的函数之间的关系感到困惑。我也尝试过包括弱存储,但据我所知,这是 @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: 更快地跳转到代码部分的转折点。

关于ios - 将开关状态绑定(bind)到 Swift 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42122126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com