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

时间:2019-05-31 10:57:33

标签: swift nsstring

说明

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

我尝试了什么

我已经实现了以下解决方案:https://stackoverflow.com/a/31613297/11582550 (请参见代码) 它也可以工作,但前提是要在控制台中打印结果。我想将文本保存在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

2 个答案:

答案 0 :(得分:0)

Instead of using low-level C functions and C strings (pointer) in Swift, I suggest using pure Swift string manipulation:

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

To cut off long strings, you could do it like this:

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

答案 1 :(得分:0)

Your issue is that you are using a proportional font instead of a fixed-width font for your label. In proportional fonts, the character widths vary, so you can't expect the characters to align.

Change the font that your label is using to a fixed-width font (such as Courier, Courier New, or Menlo) and that will fix your issue.