繁体   English   中英

如何在iOS中的电话号码数字之间放置自定义空格?

[英]How to put custom space between digits of a phone number in iOS?

我需要以这样的格式显示电话号码:+91 8346438438 到 +91 8346 4384 38。我使用以下代码来实现此功能:

  extension String {
    
      func separate(every stride: Int = 4, with separator: Character = " ") -> String {
          return String(enumerated().map { $0 > 0 && $0 % stride == 0 ? [separator, $1] : [$1]}.joined())
      }
  }

我正在将此扩展名用于这样的字符串:

text?.separate(every: 2, with: " ")

但是我只能在每 2 位数字之后获得空格,而我想以自定义方式放置空格,例如首先在 3 位数字之后然后在 4 位数字之后。 如何更改扩展以实现此目的?

首先,您需要删除原始字符串中的空格。 如果您真正想要的是定义一个开始插入字符分隔符的位置,您可以简单地检查偏移量是否等于开始偏移量或偏移量截断余数除以步幅等于开始而不是零。

extension Bool {
    var negated: Bool { !self }
}

extension StringProtocol {
    func separate(every stride: Int = 4, from start: Int = 0, with separator: Character = " ") -> String {
        .init(enumerated().flatMap { $0 != 0 && ($0 == start || $0 % stride == start) ? [separator, $1] : [$1]})
    }
}

"+91 8346438438".filter(\.isWhitespace.negated)
    .separate(every: 4, from: 3, with: " ")

编辑/更新:

class CustomField: UITextField {
    override func didMoveToWindow() {
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    }
    @objc func editingChanged() {
        text?.removeAll{ !("0"..."9" ~= $0 || $0 == "+") }
        text?.insert(separator: " ", from: 3, every: 4)
        print(text ?? "") 
    }

}

extension StringProtocol where Self: RangeReplaceableCollection {
    mutating func insert<S: StringProtocol>(separator: S, from start: Int = 0, every n: Int) {
        var distance = count
        for index in indices.dropFirst(start).reversed() {
            distance -= 1
            guard distance % n == start && index != startIndex else { continue }
            insert(contentsOf: separator, at: index)
        }
    }
}

var text = "+91 8346438438"
text.removeAll(where: \.isWhitespace)
text.insert(separator: " ", from: 3, every: 4)
print(text)  // +91 8346 4384 38

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM