diff --git a/AutocompleteField/AutocompleteField.swift b/AutocompleteField/AutocompleteField.swift index a13446e..acd7f57 100644 --- a/AutocompleteField/AutocompleteField.swift +++ b/AutocompleteField/AutocompleteField.swift @@ -19,159 +19,160 @@ public enum AutocompleteType { @IBDesignable public class AutocompleteField: UITextField { // MARK: - public properties - + // left/right padding @IBInspectable public var padding : CGFloat = 0 - + // the color of the suggestion. Matches the default placeholder color @IBInspectable public var completionColor : UIColor = UIColor(white: 0, alpha: 0.22) - + // Array of suggestions - public var suggestions : [String] = [""] - + public var suggestions: [String] = [""] + // The current suggestion shown. Can also be used to force a suggestion public var suggestion : String? { didSet { if let val = suggestion { - setLabelContent(val) + setLabelContent(text: val) } } } - + // Move the suggestion label up or down. Sometimes there's a small difference, and this can be used to fix it. public var pixelCorrection : CGFloat = 0 - + // Update the suggestion when the text is changed using 'field.text' override public var text : String? { didSet { if let text = text { - self.setLabelContent(text) + self.setLabelContent(text: text) } } } - + // The type of autocomplete that should be used public var autocompleteType : AutocompleteType = .Word - - + + // MARK: - private properties - + // the suggestion label private var label = UILabel() - - + + // MARK: - init functions - + override public init(frame: CGRect) { super.init(frame: frame) - + createNotification() setupLabel() } - + required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - + createNotification() setupLabel() } - + /** - Create an instance of a AutocompleteField. - - parameter - frame: The fields frame - suggestion: Array of autocomplete strings + Create an instance of a AutocompleteField. + - parameter + frame: The fields frame + suggestion: Array of autocomplete strings */ public init(frame: CGRect, suggestions: [String]) { super.init(frame: frame) - + self.suggestions = suggestions createNotification() setupLabel() } - - + + // ovverride to set frame of the suggestion label whenever the textfield frame changes. public override func layoutSubviews() { - self.label.frame = CGRectMake(self.padding, self.pixelCorrection, self.frame.width - (self.padding * 2), self.frame.height) + self.label.frame = CGRect(x: self.padding, y: self.pixelCorrection, width: self.frame.width - (self.padding * 2), height: self.frame.height) super.layoutSubviews() } - + // MARK: - public methods public func currentSuggestion() -> NSString? { - return self.suggestion + return self.suggestion as NSString? } - - + + // MARK: - private methods - + /** - Create a notification whenever the text of the field changes. - */ + Create a notification whenever the text of the field changes. + */ private func createNotification() { - NSNotificationCenter.defaultCenter().addObserver( + NotificationCenter.default.addObserver( self, - selector: "textChanged:", - name: UITextFieldTextDidChangeNotification, + selector: #selector(textChanged(notification:)), + name: NSNotification.Name.UITextFieldTextDidChange, object: self) } - + /** - Sets up the suggestion label with the same font styling and alignment as the textfield. - */ + Sets up the suggestion label with the same font styling and alignment as the textfield. + */ private func setupLabel() { setLabelContent() - - self.label.lineBreakMode = .ByClipping + + self.label.lineBreakMode = .byClipping // If the textfield has one of the default styles, we need to create some padding // otherwise there will be a offset in x-led. switch self.borderStyle { - case .RoundedRect, .Bezel, .Line: - self.padding = 8 - break; - default: + case .roundedRect, .bezel, .line: + self.padding = 8 + break; + default: break; } - + self.addSubview(self.label) } - - + + /** - Set content of the suggestion label. - - parameter text: Suggestion text - */ - private func setLabelContent(var text : String = "") + Set content of the suggestion label. + - parameter text: Suggestion text + */ + private func setLabelContent( text : String = "") { // label string + var text = text if(text.characters.count < 1) { label.attributedText = nil return } - + // only return first word if in word mode if(self.autocompleteType == .Word) { - let words = self.text!.componentsSeparatedByString(" ") - let suggestionWords = text.componentsSeparatedByString(" ") + let words = self.text!.components(separatedBy: " ") + let suggestionWords = self.text!.components(separatedBy: " ") var string : String = "" - for(var i = 0; i < words.count; i++) + for i in 0 ..< words.count { - string = string.stringByAppendingString(suggestionWords[i]) + " " + string = string.appending(suggestionWords[i]) + " " } text = string } - - // create an attributed string instead of the regular one. + + // create an attributed string instead of the regular one. // In this way we can hide the letters in the suggestion that the user has already written. let attributedString = NSMutableAttributedString( string: text, @@ -183,41 +184,39 @@ public enum AutocompleteType { NSForegroundColorAttributeName: self.completionColor ] ) - + // Hide the letters that are under the fields text. // If the suggestion is abcdefgh and the user has written abcd // we want to hide those letters from the suggestion. if let inputText = self.text { attributedString.addAttribute(NSForegroundColorAttributeName, - value: UIColor.clearColor(), - range: NSRange(location:0, length:inputText.characters.count) + value: UIColor.clear, + range: NSRange(location:0, length:inputText.characters.count) ) } - + label.attributedText = attributedString label.textAlignment = self.textAlignment } - + /** - Scans through the suggestions array and finds a suggestion that - matches the searchTerm. - - parameter searchTerm: What to search for - - returns A string or nil + Scans through the suggestions array and finds a suggestion that + matches the searchTerm. + - parameter searchTerm: What to search for + - returns A string or nil */ private func suggestionToShow(searchTerm : String) -> String { var returnString = "" - for suggestion in self.suggestions - { - // Search the suggestion array. User lowercase on both to get a match. + for suggestion in self.suggestions { + // Search the suggestion array. User lowercase on both to get a match. // Also, if the match is exact we move on. - if( (suggestion != searchTerm) && - suggestion.lowercaseString.hasPrefix(searchTerm.lowercaseString)) - { + if suggestion != searchTerm && suggestion.lowercased().hasPrefix(searchTerm.lowercased()) { var suggestionToReturn = searchTerm - suggestionToReturn = suggestionToReturn + suggestion.substringWithRange(Range(start: suggestion.startIndex.advancedBy(searchTerm.characters.count), end: suggestion.endIndex)) + let range = Range(suggestion.index(suggestion.startIndex, offsetBy: searchTerm.characters.count).. CGRect + public override func textRect(forBounds bounds: CGRect) -> CGRect { - return CGRectMake(bounds.origin.x + self.padding, bounds.origin.y, - bounds.size.width - (self.padding * 2), bounds.size.height); + return CGRect(x: bounds.origin.x + self.padding, y: bounds.origin.y, + width: bounds.size.width - (self.padding * 2), height: bounds.size.height); } - + // ovverride to set padding - public override func editingRectForBounds(bounds: CGRect) -> CGRect + public override func editingRect(forBounds bounds: CGRect) -> CGRect { - return self.textRectForBounds(bounds) + return self.textRect(forBounds: bounds) } - + // ovverride to set padding on placeholder - public override func placeholderRectForBounds(bounds: CGRect) -> CGRect + public override func placeholderRect(forBounds bounds: CGRect) -> CGRect { - return self.textRectForBounds(bounds) + return self.textRect(forBounds: bounds) } // remove observer on deinit deinit { - NSNotificationCenter.defaultCenter().removeObserver(self) + NotificationCenter.default.removeObserver(self) } } diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 98bb2e9..91b3914 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -94,11 +94,13 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0710; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = "Filip Stefansson"; TargetAttributes = { 5A0A453E1BEBD6CD000BFC25 = { CreatedOnToolsVersion = 7.1; + LastSwiftMigration = 0800; + ProvisioningStyle = Manual; }; }; }; @@ -179,8 +181,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -224,8 +228,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -244,6 +250,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.1; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -253,10 +260,12 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = Example/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pixbymedia.Example; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -264,10 +273,12 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = Example/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pixbymedia.Example; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -290,6 +301,7 @@ 5A0A45531BEBD6CD000BFC25 /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index ef496c0..a06dadb 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -14,33 +14,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { - // Override point for customization after application launch. + private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } - func applicationWillResignActive(application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - } - - func applicationDidEnterBackground(application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - } - - func applicationWillEnterForeground(application: UIApplication) { - // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. - } - - func applicationDidBecomeActive(application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - } - - func applicationWillTerminate(application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. - } - - } diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index 374e37f..805fd61 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -33,15 +33,15 @@ class ViewController: UITableViewController, UITextFieldDelegate { customField.suggestions = suggestions // change event for email field - NSNotificationCenter.defaultCenter().addObserver( + NotificationCenter.default.addObserver( self, - selector: "emailChanged:", - name: UITextFieldTextDidChangeNotification, + selector: #selector(emailChanged(notification:)), + name: NSNotification.Name.UITextFieldTextDidChange, object: emailField) // add code example - let textField = AutocompleteField(frame: CGRectMake(0, 0, self.codeView.frame.size.width, self.codeView.frame.size.height), suggestions: ["abraham"]) + let textField = AutocompleteField(frame: CGRect(x: 0, y: 0, width: self.codeView.frame.size.width, height: self.codeView.frame.size.height), suggestions: ["abraham"]) textField.padding = 8 textField.placeholder = "Try typing 'A'" @@ -49,11 +49,11 @@ class ViewController: UITableViewController, UITextFieldDelegate { self.codeView.addSubview(textField) // auto layout - let vertivalConstraint = textField.centerYAnchor.constraintEqualToAnchor(self.codeView.centerYAnchor) - let leadingConstraint = textField.leadingAnchor.constraintEqualToAnchor(self.codeView.leadingAnchor, constant: 10) - let trailingConstraint = textField.trailingAnchor.constraintEqualToAnchor(self.codeView.trailingAnchor, constant: -10) - let heightConstraint = textField.heightAnchor.constraintEqualToAnchor(nil, constant: 37) - NSLayoutConstraint.activateConstraints([leadingConstraint, vertivalConstraint, trailingConstraint, heightConstraint]) + let vertivalConstraint = textField.centerYAnchor.constraint(equalTo: self.codeView.centerYAnchor) + let leadingConstraint = textField.leadingAnchor.constraint(equalTo: self.codeView.leadingAnchor, constant: 10) + let trailingConstraint = textField.trailingAnchor.constraint(equalTo: self.codeView.trailingAnchor, constant: -10) + let heightConstraint = textField.heightAnchor.constraint(equalTo: self.codeView.heightAnchor, constant: 37) + NSLayoutConstraint.activate([leadingConstraint, vertivalConstraint, trailingConstraint, heightConstraint]) } func emailChanged(notification: NSNotification) @@ -64,14 +64,15 @@ class ViewController: UITableViewController, UITextFieldDelegate { { // Check if the user has started writing the suffix yet. var suffix = "@gmail.com" - let regex = try! NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@",options: [.CaseInsensitive]) - let result = regex.firstMatchInString(text, options:[], range: NSMakeRange(0, text.characters.count)) + let regex = try! NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@",options: [.caseInsensitive]) + let result = regex.firstMatch(in: text, options:[], range: NSMakeRange(0, text.characters.count)) if let range = result?.range { // If user has started writing the suffix, only suggest what's left of it - let regSuffix = text.substringWithRange(Range(start: text.startIndex.advancedBy(range.length - 1), end: text.endIndex)) - suffix = suffix.stringByReplacingOccurrencesOfString(regSuffix, withString: "") + let range = Range(text.index(text.startIndex, offsetBy: range.length - 1).. Bool + func textFieldShouldReturn(_ textField: UITextField) -> Bool { // set field text to the suggestion text on return if let field = textField as? AutocompleteField