我有一个应用程序的开头,人们可以在他们将要发出的演讲中输入单词的数量,并且它将根据谈话速度计算演讲将花费多长时间。我希望应用程序能够存储变量“sum”的唯一十进制值,以便我可以将其转换为分钟和秒。这是下面的一个按钮的代码和UI的快照,提前谢谢你。 http://imgur.com/gallery/ZmKtekJ/new
@IBAction func slow(sender: UIButton) {
let buttonPressed : Bool = true
let a = (text1.text as NSString!).doubleValue
let b : Int = 100
let sum = Float(a) / Float(b)
result.text = "\(sum) minutes"
if sum >= 60 {
let hour = Float(sum) / Float(60.0)
let sum = "\(hour)"
result.text = "\(sum) hours"
}
if buttonPressed {
self.view.endEditing(true)
}
}
答案 0 :(得分:1)
您可以使用%
运算符,它可以为您提供“休息”功能。例如:
70 % 60.0 = 10
修改强>
不确定你想通过字符串doubleValue
得到什么,但我在我的例子中使用了字符数:
@IBAction func slow(sender: UIButton) {
let buttonPressed = true
let a = text1.text!.characters.count
let b = 100
let sum = a / b
result.text = "\(sum) minutes"
if sum >= 60 {
let h = sum / 60
let m = sum % 60
if m != 0 {
result.text = "\(h) hours and \(m) minutes"
} else {
result.text = "\(h) hours"
}
} else {
result.text = "\(sum) minutes"
}
if buttonPressed {
view.endEditing(true)
}
}
答案 1 :(得分:0)
@IBAction func slow(sender: UIButton) {
let buttonPressed = true
// stores input in var a as a double
var a = double(text1.text)!
// defines constant b
let b = 100
// calculates sum
var sum = a / b
//calculates hours
var hours = sum / 60
//calculates minutes
var minutes = sum % 60
// if there are 1 or more hours and 1 or more minutes result displays
// hours and minutes
if hours > 0 && minutes != 0 {
result.text = "\(hours) hours and \(minutes) minutes"
//if there are no minutes result just displays hours
} else if minutes == 0{
result.text = "\(hours) hours"
//if there are no hours result just displays minutes
} else if hours == 0 {
result.text = "\(minutes) minutes"
}
您可能还想进行一些输入验证,以确保用户不会输入会导致整个房屋倒塌的字母。