如何格式化多个字符串,使它们彼此齐平

How to format multiple Strings so that they are flush with each other

描述

我想格式化多个字符串,使它们彼此齐平。 (查看实际结果和预期结果)

我试过的

我已经实施了这个解决方案: (见代码) 它也有效,但前提是我在控制台中打印结果。我想将文本保存在 label.text 中,这不起作用。

一些代码

func formattedString(left:String, right:String) -> String {
        let left = (left as NSString).utf8String
        let right = (right as NSString).utf8String
        print(String(format:"%-20s %-20s", left!, right!))
        return String(format:"%-20s %-20s", left!, right!)
    }

label.text += formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")

// actual result

如我所料

## actual result (saved in label.text)
Firstname:    Alfred
Lastname:    LongLastname
Note:    private

## expected result (saved in label.text)
Firstname:    Alfred
Lastname:     LongLastname
Note:         private

我建议不要在 Swift 中使用 low-level C 函数和 C 字符串(指针),而是使用纯 Swift 字符串操作:

func formattedString(left: String, right: String, width: Int = 20) -> String {
    // The `max` call returns 0 if `width - left.count` is negative
    let filler = String(repeating: " ", count: max(0, width - left.count))
    return left + filler + right
}

let result = formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")
print(result)

// Firstname:          Alfred
// Lastname:           LongLastname
// Note:               private

要切断长字符串,你可以这样做:

func limit(string: String, length: Int) -> String {
    if string.count <= length {
        return string
    }
    return string.prefix(length) + "…"
}

您的问题是您使用的是比例字体而不是标签的 fixed-width 字体。在比例字体中,字符宽度不同,因此您不能指望字符对齐。

将标签使用的字体更改为 fixed-width 字体(例如 CourierCourier New,或Menlo),这将解决您的问题。