我试图从我的标签中获取int值并将它们传递给另一个标签并将它们添加到一起。在下面的代码kicklabel
,handballlabel
,marklabel
等中,所有内容都需要加起来并等于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]!)"
}
}
答案 0 :(得分:0)
在didSwipe
结束时,您需要汇总Int
字典中存储的所有counters
值。然后使用该总和更新您的fantasy
标签。
let sum = counters.reduce(0) { $0 + $1.value }
fantasyLabel.text = "\(sum)"
你可能不希望fantasy
标签上的手势,因为该值是基于其他数据总和的只读。
除了fantasy
标签外,我还会删除各个标签出口。使用IBOutletCollect存储UILabel
的数组。