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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With