当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Dynamically Calculate Pace in Swift

问题描述:

I have this code below. How would dynamically calculate the pace as I fill in the fields instead of having to calculate it manually by tapping on the Calculate Pace button?

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var minTextField: UITextField!

@IBOutlet weak var secTextField: UITextField!

@IBOutlet weak var distTextField: UITextField!

@IBOutlet weak var paceLabel: UILabel!

func paceInSeconds (minutes:Double, seconds: Double, distance: Double) -> Double {

return ((minutes*60) + seconds) / distance

}

@IBAction func paceCalculator(sender: UIButton) {

var paceMinutes = paceInSeconds(((minTextField.text as NSString).doubleValue, seconds: (secTextField.text as NSString).doubleValue, distance: (distTextField.text as NSString).doubleValue)) / 60

var roundedPaceMinutes = Double(floor(paceMinutes))

var decimalPaceSeconds = paceMinutes - roundedPaceMinutes

var intPaceMinutes = Int(floor(roundedPaceMinutes))

var paceSeconds = Int(floor(decimalPaceSeconds * 60))

var paceSecondsZero = String(format: "%02d", paceSeconds)

paceLabel.text = "\(intPaceMinutes):\(paceSecondsZero)/km"

}

}

Here's the storyboard UI:

网友答案:

You can use the various functions of the UITextFieldDelegate protocol. If you assign your view controller as the delegate of the text field, it will be able to act upon changes in the text field.

In your case, you should implement the textField:shouldChangeCharactersInRange:replacementString: function.

分享给朋友:
您可能感兴趣的文章:
随机阅读: