【问题标题】:Multiplication table in Swift iosSwift ios中的乘法表
【发布时间】:2016-09-01 07:13:48
【问题描述】:
我正在学习如何快速制作乘法表并使用
override func viewDidLoad() {
let n = Int(str)!
while (i<=10) {
let st = "\(n) * \(i) = \(n * i)"
lbl.text = st
i += 1
}
这段代码。我有一个标签,我想在其中显示表格,但问题是只显示最后一个结果,即 2*10 = 20,而不是所有其他值。我很困惑该怎么做,请帮助显示所有值。
【问题讨论】:
标签:
ios
iphone
xcode
swift
【解决方案1】:
很高兴您决定学习 Swift。您走在正确的轨道上,但正如其他人所说,您循环的最后一次迭代正在替换 lbl.text 的内容。
有很多方法可以实现你想要的,但对于这样的问题,我建议从操场开始工作,而不是担心标签、viewDidLoad 等。
这是一种很好的 Swift-y 方式来做你想做的事
let n = 12
let table = Array(0...10).map({"\(n) * \($0) = \(n * $0)"}).joinWithSeparator("\n")
print("\(table)")
给……
12 * 0 = 0
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120
分解它...
// Take numbers 0 to 10 and make an array
Array(0...10).
// use the map function to convert each member of the array to a string
// $0 represents each value in turn.
// The result is an array of strings
map({"\(n) * \($0) = \(n * $0)"}).
// Join all the members of your `String` array with a newline character
joinWithSeparator("\n")
自己试试吧。在 Xcode 中,File -> New -> Playground,然后粘贴该代码。祝你好运!
【解决方案2】:
这是因为每次循环迭代时,它都会覆盖 label.text 中的先前值。您需要按照 RichardG 的建议将新值附加到标签中的现有字符串值。
let n = Int(str)!
while (i<=10) {
let st = "\(n) * \(i) = \(n * i)"
lbl.text = lbl.text + " " +st //Append new value to already existing value in label.text
i += 1
}
还有可能是 UI 问题。您必须为标签提供行数,否则会弄乱显示。它还需要足够大以容纳您的数据。如果您不愿意处理标签高度和宽度的情况,更好的选择是UITextView,它是可滚动的。但是如果你想坚持使用UILabel,下面的代码会根据你的文本调整标签的大小:
lbl.numberOfLines = 0; //You only need to call this once. Maybe in `viewDidLoad` or Storyboard itself.
lbl.text = @"Some long long long text"; //here you set the text to label
[lbl sizeToFit]; //You must call this method after setting text to label
您也可以通过Autolayout constraints 处理。
【解决方案3】:
使用 SWIFT 2.0 轻松实现
var tableOf = 2 //Change the table you want
for index in 1...10 {
print("\(tableOf) X \(index) = \(index * tableOf)")
}
输出
【解决方案4】:
repeat-while 循环,在考虑循环条件之前先执行一次循环块。
1) 重复...while循环
var i = Int()
repeat {
print("\(i) * \(i) = \(i * 11)")
i += 1
} while i <= 11
2) While 循环
var i = Int()
while i <= 11
{
print("\(i) * \(i) = \(i * 11)")
i += 1
}
3) For 循环
for n in 1..<11
{
print("\(n) * \(n) = \(n * 10)")
}