单个标签在刷卡时更新值

时间:2018-05-17 23:15:20

标签: ios swift

由于一些很好的帮助,我现在可以在单个标签上使用我的滑动功能!现在我只需要在刷卡时单独更新每个标签,因此每个标签都有自己独立的计数器而不影响其他标签。

继承我的代码:

导入UIKit

class ViewController: UIViewController {

    var counter = 0

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!

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

    override func viewDidLoad() {
        super.viewDidLoad()

        for label: UILabel in [label1, label2, label3] {

            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]! + 5
            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:
            label.text = "0"
        }
    }

}

2 个答案:

答案 0 :(得分:0)

我知道如何在手势结束时设置文本的标签。

label.text =“(counter [label]!)”

例如,

@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]! + 5
        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]!)”
}

答案 1 :(得分:0)

您需要致电

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

在switch语句结束时。这应该有用。