我遇到了这个问题,我在网上寻找的所有可能的解决方案都没有帮助我。有没有办法制作类似字符串格式的表格?
我期望字符串的输出如下:
Category
ITEM1 QTY PRICE TOTAL
ITEM2 QTY PRICE TOTAL
但是我的输出代码是这样的:
Category
ITEM1 QTY PRICE TOTAL
ITEM2 QTY PRICE TOTAL
Category
ITEM1 QTY PRICE TOTAL
ITEM2 QTY PRICE TOTAL
我发现项目字符串长度是它们没有以我的格式正式对齐的成本,但是有没有办法解决这个问题?我是 swift 的新手。
这是我的代码:
for category in self.categoryList {
sentence += "Category: \(category)\n"
for items in self.productList {
if category == items.category {
grandTotal += Double(items.qty)! * Double(items.price)!
let total: Double = Double(items.qty)! * Double(items.price)!
let item = (items.item as NSString).utf8String
let qty = (items.qty as NSString).utf8String
let price = (items.price as NSString).utf8String
sentence += String(format: "%-10s%20s%15s%15.02f\n", item!, qty!, price!, total)
}
}
sentence += "\n\n"
grandTotal = 0
}
lblData.text = sentence
最佳答案
您可以将字符串填充到定义的长度:
let elements = ["ITEM1", "QTY", "PRICE", "TOTAL"]
// without padding
var sentence = ""
for e in elements {
if !sentence.isEmpty {
sentence += " "
}
sentence += e
}
print(sentence)
// prints "ITEM1 QTY PRICE TOTAL"
// with padding
sentence = ""
for e in elements {
sentence += e.padding(toLength: 10, withPad: " ", startingAt: 0)
}
print(sentence)
// prints "ITEM1 QTY PRICE TOTAL "
或者更简短的形式:
// without padding
var sentence = elements.joined(separator: " ")
print(sentence)
// with padding
sentence = elements.map({$0.padding(toLength: 10, withPad: " ", startingAt: 0)}).joined(separator: " ")
print(sentence)
关于ios - 字符串格式就像循环中的表 swift4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58196277/