Last active
July 4, 2016 19:58
-
-
Save robertmryan/998a452a9a83eb4dbec4bebd2da52337 to your computer and use it in GitHub Desktop.
Formatter validation in Swift for Cocoa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// | |
// Created by Robert Ryan on 7/4/16. | |
// Copyright © 2016 Robert Ryan. All rights reserved. | |
// | |
import Cocoa | |
class TwoDigitFormatter: NumberFormatter { | |
let maxLength = 2 | |
let wrongCharacterSet = CharacterSet(charactersIn: "0123456789").inverted | |
override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { | |
if partialString.characters.count > maxLength { | |
return false | |
} | |
if partialString.rangeOfCharacter(from: wrongCharacterSet) != nil { | |
return false | |
} | |
return true | |
} | |
override func attributedString(for obj: AnyObject, withDefaultAttributes attrs: [String : AnyObject]? = [:]) -> AttributedString? { | |
let stringVal = string(for: obj) | |
guard let string = stringVal else { return nil } | |
return AttributedString(string: string, attributes: attributes) | |
} | |
var attributes: [String: AnyObject] { | |
let style = NSMutableParagraphStyle() | |
style.minimumLineHeight = 100 | |
style.maximumLineHeight = 100 | |
style.paragraphSpacingBefore = 0 | |
style.paragraphSpacing = 0 | |
style.alignment = .center | |
style.lineHeightMultiple = 1.0 | |
style.lineBreakMode = .byTruncatingTail | |
let droidSansMono = NSFont(name: "DroidSansMono", size: 70)! | |
return [NSParagraphStyleAttributeName: style, NSFontAttributeName: droidSansMono, NSBaselineOffsetAttributeName: -60] | |
} | |
} | |
class ViewController: NSViewController, NSTextFieldDelegate { | |
@IBOutlet weak var textField: NSTextField! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
textField.formatter = TwoDigitFormatter() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Re http://stackoverflow.com/questions/38190958/how-to-use-a-nsnumberformatter-with-an-attributedstring