2016-12-03 14 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のchunk(n:) methodCollectionのための年代)のスウィフト3バージョンを実装することにより開始することができます。■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 
} 

注:Space代わりの- (Hyphen)をしたい場合は、私が使用している- (Hyphen)あなたは、単にSpaceに置き換えることができます。

関連する問題