Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

align left and right in the same line swift

I want to align texts left and right on the same line in swift. For example, I have a string with product names to the left and the price to the right. Both on the same line. Is this possible?

I need this for bluetooth printing, where every line has exactly 32 characters.

like image 618
Salihan Pamuk Avatar asked Sep 03 '25 17:09

Salihan Pamuk


1 Answers

If I understand correctly, you want something like this:

func alignLeftAndRight(left: String, right: String, length: Int) -> String {
    // calculate how many spaces are needed
    let numberOfSpacesToAdd = length - left.count - right.count

    // create those spaces
    let spaces = Array(repeating: " ", count: numberOfSpacesToAdd < 0 ? 0 : numberOfSpacesToAdd).joined()

    // join these three things together
    return left + spaces + right
}

Usage:

print(alignLeftAndRight(left: "Product", right: "Price", length: 32))
print(alignLeftAndRight(left: "Foo", right: "1", length: 32))
print(alignLeftAndRight(left: "Product", right: "123", length: 32))
print(alignLeftAndRight(left: "Something", right: "44", length: 32))
print(alignLeftAndRight(left: "Hello", right: "7777", length: 32))

Output:

Product                    Price
Foo                            1
Product                      123
Something                     44
Hello                       7777
like image 107
Sweeper Avatar answered Sep 07 '25 07:09

Sweeper