gpt4 book ai didi

ios - 从标签中获取值并将其添加到另一个标签中

转载 作者:行者123 更新时间:2023-11-30 11:29:05 25 4
gpt4 key购买 nike

我试图从我的标签中获取 int 值并将它们传递给另一个标签并将它们添加在一起。下面的代码中,kicklabelhandballlabelmarklabel等都需要相加等于fantasylabel。根据此代码的设置方式,我不确定如何执行该操作。

我还希望能够添加更多行标签,以便将任意数量的标签数组添加到幻想标签中。

代码如下:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var kickLabel1: UILabel!
@IBOutlet weak var handballLabel1: UILabel!
@IBOutlet weak var markLabel1: UILabel!
@IBOutlet weak var tackleLabel1: UILabel!
@IBOutlet weak var goalLabel1: UILabel!
@IBOutlet weak var pointLabel1: UILabel!
@IBOutlet weak var freeForLabel1: UILabel!
@IBOutlet weak var freeAgainstLabel1: UILabel!
@IBOutlet weak var fantasyLabel: UILabel!

var counters: [UILabel: Int] = [:]

override func viewDidLoad() {
super.viewDidLoad()

for label: UILabel in [kickLabel1,handballLabel1,markLabel1,tackleLabel1,goalLabel1,pointLabel1, freeForLabel1, freeAgainstLabel1, fantasyLabel] {
counters[label] = 0

for direction: UISwipeGestureRecognizerDirection in [.up, .down, .left, .right] {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(didSwipe(_:)))
swipeGesture.direction = direction
label.addGestureRecognizer(swipeGesture)
label.isUserInteractionEnabled = true
label.isMultipleTouchEnabled = true
}
}
}

@objc func didSwipe(_ gestureRecognizer: UISwipeGestureRecognizer) {
guard let label = gestureRecognizer.view as? UILabel else { return }

debugPrint("\(gestureRecognizer.direction)")

switch gestureRecognizer.direction {
case .up:
counters[label] = counters[label]! + 10
print(counters)
case .down:
counters[label] = 0
print(counters)
case .left:
counters[label] = counters[label]! - 1
print(counters)
case .right:
counters[label] = counters[label]! + 1
print(counters)
default:
counters[label] = 0
}

label.text = "\(counters[label]!)"
}
}

最佳答案

didSwipe 结束时,您需要对 counters 字典中存储的所有 Int 值求和。然后用该总和更新您的fantasy标签。

let sum = counters.reduce(0) { $0 + $1.value }
fantasyLabel.text = "\(sum)"

您可能不希望在 fantasy 标签上使用手势,因为该值是基于其他数据总和的只读值。

除了fantasy标签之外,我还会去掉其他单独的标签。使用 IBOutletCollect 存储 UILabel 数组。

关于ios - 从标签中获取值并将其添加到另一个标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50442472/

25 4 0