我想将UIView中的一些字符串用于一个字符,如下所示:
1 - 4
5 - 11
12 - 50
51 - 225
或者:
1 - 4
5 - 11
12 - 50
51 - 225
或者:
1-4
5-11
12-50
51-225
使用%3d
和myView.textAlignment = .center
对每个字符串进行格式化后,结果如下所示:
1-4
5-11
12-50
51-225
Swift是否有其他内置的对齐选项(如左对齐、居中对齐和右对齐)来执行此操作?如果不是,有什么简单的方法吗?
发布于 2020-08-26 09:11:29
只需创建一个helper来向左或向右填充字符串直到所需的长度,并填充您的下限和上限
extension StringProtocol where Self: RangeReplaceableCollection {
func paddingLeft(upTo length: Int = 3) -> Self {
repeatElement(" ", count: Swift.max(0, length-count)) + self
}
func paddingRight(upTo length: Int = 3) -> Self {
self + repeatElement(" ", count: Swift.max(0, length-count))
}
}
类似于:
let numbers = "1-4\n5-11\n12-50\n51-225"
let lines = numbers.split(whereSeparator: \.isNewline)
let components = lines.map{$0.components(separatedBy: "-")}
let padded = components.map{
($0.first?.paddingLeft() ?? "") + "-" + ($0.last?.paddingRight() ?? "")
}.joined(separator: "\n")
print(padded) // " 1-4 \n 5-11 \n 12-50 \n 51-225\n"
这将打印以下内容:
1-4
5-11
12-50
51-225
https://stackoverflow.com/questions/63588981
复制相似问题