2016-12-03 186 views
2

我有一個textfield,最大字符範圍爲16,我想在每4個字符後加上減號字符或空格,然後寫入其他字符,例如5022-2222- 2222-2222。 有我的代碼,但這是行不通的,怎麼能做到這一點?在輸入文本字段時在文本字符之間添加空格

if textField.text?.characters.count == 5 { 

       let l = textField.text?.characters.count 
      let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!) 
      attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4)) 
      cartNumberTextField.attributedText = attributedString 

      } 

      else if textField.text?.characters.count == 9 { 

       let l = textField.text?.characters.count 
       let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!) 
       attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4)) 
       cartNumberTextField.attributedText = attributedString 

      } 

      else if textField.text?.characters.count == 13 { 

       let l = textField.text?.characters.count 
       let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!) 
       attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4)) 
       cartNumberTextField.attributedText = attributedString 

      } 

我在UITextFieldshouldChangeCharactersIn範圍的方法,添加以下代碼。

回答

4

我們可以通過實施oisdk的斯威夫特3版chunk(n:) method(用於Collection的)的啓動:■SwiftSequence

/* Swift 3 version of Github use oisdk:s SwiftSequence's 'chunk' method: 
    https://github.com/oisdk/SwiftSequence/blob/master/Sources/ChunkWindowSplit.swift */ 
extension Collection { 
    public func chunk(n: IndexDistance) -> [SubSequence] { 
     var res: [SubSequence] = [] 
     var i = startIndex 
     var j: Index 
     while i != endIndex { 
      j = index(i, offsetBy: n, limitedBy: endIndex) ?? endIndex 
      res.append(self[i..<j]) 
      i = j 
     } 
     return res 
    } 
} 

在這種情況下,實現您的自定義格式是創造4-一個簡單的例子字符塊和通過接合這些 「 - 」:

func customStringFormatting(of str: String) -> String { 
    return str.characters.chunk(n: 4) 
     .map{ String($0) }.joined(separator: "-") 
} 

實例:

print(customStringFormatting(of: "5022222222222222")) // 5022-2222-2222-2222 
print(customStringFormatting(of: "50222222222222")) // 5022-2222-2222-22 
print(customStringFormatting(of: "5022222"))   // 5022-222 

如果申請在UITextFieldDelegatetextField(_:shouldChangeCharactersIn:replacementString:)方法一起使用,我們可能要過濾掉存在於customStringFormatting(of:)方法方法分離,以及其實現爲String擴展:

extension String { 
    func chunkFormatted(withChunkSize chunkSize: Int = 4, 
     withSeparator separator: Character = "-") -> String { 
     return characters.filter { $0 != separator }.chunk(n: chunkSize) 
      .map{ String($0) }.joined(separator: String(separator)) 
    } 
} 

而且實施文本字段的受控更新,例如如下:

let maxNumberOfCharacters = 16 

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    // only allow numerical characters 
    guard string.characters.flatMap({ Int(String($0)) }).count == 
     string.characters.count else { return false } 

    let text = textField.text ?? "" 

    if string.characters.count == 0 { 
     textField.text = String(text.characters.dropLast()).chunkFormatted() 
    } 
    else { 
     let newText = String((text + string).characters 
      .filter({ $0 != "-" }).prefix(maxNumberOfCharacters)) 
     textField.text = newText.chunkFormatted() 
    } 
    return false 
} 

最後一部分上面將截斷可能粘貼字符串從用戶(假定它的所有數字),例如

// current 
1234-1234-123 

// user paste: 
777777777 
    /* ^^^^ will not be included due to truncation */ 

// will result in 
1234-1234-1237-7777 
3

像這樣使用shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

    if textField.text?.characters.count == 4 && string.characters.count != 0 { 
     textField.text = textField.text! + "-" 
    } 
    else if textField.text?.characters.count == 6 && string.characters.count == 0 { 
     textField.text = String(textField.text!.characters.dropLast()) 
    } 
    else if textField.text?.characters.count == 9 && string.characters.count != 0 { 
     textField.text = textField.text! + "-" 
    } 
    else if textField.text?.characters.count == 11 && string.characters.count == 0{ 
     textField.text = String(textField.text!.characters.dropLast()) 
    } 
    else if textField.text?.characters.count == 14 && string.characters.count != 0 { 
     textField.text = textField.text! + "-" 
    } 
    else if textField.text?.characters.count == 16 && string.characters.count == 0 { 
     textField.text = String(textField.text!.characters.dropLast()) 
    } 
    if textField.text?.characters.count == 19 && string.characters.count != 0 { 
     return false 
    } 
    return true 
} 

注:我用- (Hyphen)你可以簡單地用Space替換它,如果你想Space,而不是- (Hyphen)

相關問題