Victor Victor - 18 days ago 6
Swift Question

NSTextField Mask (Swift 2.2)

Does anyone know how to implement a

NSTextField
mask in Swift? Need to do a MAC address mask for it.

Answer

This should get you going.

class MacAddressFormatter : NSFormatter {
  override func stringForObjectValue(obj: AnyObject?) -> String? {
    if let string = obj as? String {
      return string
    }
    return nil
  }

  override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
    if obj != nil {
      obj.memory = string
    }
    return true
  }

  override func isPartialStringValid(partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {

    if partialString.isEmpty { return true }  //allow empty field
    if partialString.characters.count > 17 { return false }  //don't allow too many chars

    let disallowedChars = NSCharacterSet(charactersInString: "0123456789ABCDEFabcdef:").invertedSet
    if let _ = partialString.rangeOfCharacterFromSet(disallowedChars, options: .CaseInsensitiveSearch) {
      error.memory = "Invalid entry.  MAC Address can only contain 0-9 & A-F"
      return false }

    var string = ""
    for char in partialString.characters {
      if char != ":" {
        string = string + String(char)
        if string.characters.count % 3 == 0 {
          string.insert(":", atIndex: string.endIndex.advancedBy(-1))
        }
      }
    }
    newString.memory = string.uppercaseString
    return false
  }
}

Just assign this formatter to you NSTextField and give it a try!