diff --git a/.gitignore b/.gitignore index 441ab05..5fa72a3 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ # Swift Package Manager .swiftpm + +# Stock +/Assets/Stock/ diff --git a/Assets/Readme/preview.png b/Assets/Readme/preview.png new file mode 100644 index 0000000..7a26084 Binary files /dev/null and b/Assets/Readme/preview.png differ diff --git a/Example Apps/SPIndicator.xcodeproj/project.pbxproj b/Example Apps/SPIndicator.xcodeproj/project.pbxproj index 2c06e66..775c190 100644 --- a/Example Apps/SPIndicator.xcodeproj/project.pbxproj +++ b/Example Apps/SPIndicator.xcodeproj/project.pbxproj @@ -10,7 +10,9 @@ F43F829D26578DCA001D9B3D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F43F829426578DCA001D9B3D /* Assets.xcassets */; }; F43F829E26578DCA001D9B3D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F43F829526578DCA001D9B3D /* LaunchScreen.storyboard */; }; F43F829F26578DCA001D9B3D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F43F829726578DCA001D9B3D /* AppDelegate.swift */; }; - F43F82A126578DCA001D9B3D /* RootController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F43F829B26578DCA001D9B3D /* RootController.swift */; }; + F43F82A126578DCA001D9B3D /* PresetsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F43F829B26578DCA001D9B3D /* PresetsController.swift */; }; + F4B96F99265AC34400A01A29 /* SPDiffable in Frameworks */ = {isa = PBXBuildFile; productRef = F4B96F98265AC34400A01A29 /* SPDiffable */; }; + F4B96F9C265AC36F00A01A29 /* IndicatorPresetModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4B96F9B265AC36F00A01A29 /* IndicatorPresetModel.swift */; }; F4BAA4352658292F00DA5BF7 /* SparrowKit in Frameworks */ = {isa = PBXBuildFile; productRef = F4BAA4342658292F00DA5BF7 /* SparrowKit */; }; F4BAA4372658293600DA5BF7 /* SPIndicator in Frameworks */ = {isa = PBXBuildFile; productRef = F4BAA4362658293600DA5BF7 /* SPIndicator */; }; F4BAA4392658293F00DA5BF7 /* SparrowKit in Frameworks */ = {isa = PBXBuildFile; productRef = F4BAA4382658293F00DA5BF7 /* SparrowKit */; }; @@ -38,11 +40,12 @@ F43F829426578DCA001D9B3D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; F43F829626578DCA001D9B3D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; F43F829726578DCA001D9B3D /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - F43F829B26578DCA001D9B3D /* RootController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RootController.swift; sourceTree = ""; }; + F43F829B26578DCA001D9B3D /* PresetsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PresetsController.swift; sourceTree = ""; }; F43F829C26578DCA001D9B3D /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F43F82AB26578F03001D9B3D /* tvOS Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "tvOS Example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; F43F82B926578F04001D9B3D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F43F83452658286B001D9B3D /* SPIndicator */ = {isa = PBXFileReference; lastKnownFileType = folder; name = SPIndicator; path = ..; sourceTree = ""; }; + F4B96F9B265AC36F00A01A29 /* IndicatorPresetModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndicatorPresetModel.swift; sourceTree = ""; }; F4BAA43D2658297300DA5BF7 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; F4BAA43E2658297300DA5BF7 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; F4BAA43F2658297300DA5BF7 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -53,6 +56,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + F4B96F99265AC34400A01A29 /* SPDiffable in Frameworks */, F4BAA4352658292F00DA5BF7 /* SparrowKit in Frameworks */, F4BAA4372658293600DA5BF7 /* SPIndicator in Frameworks */, ); @@ -94,6 +98,7 @@ isa = PBXGroup; children = ( F43F829326578DCA001D9B3D /* App */, + F4B96F9A265AC36800A01A29 /* Models */, F43F829A26578DCA001D9B3D /* Scenes */, F43F829C26578DCA001D9B3D /* Info.plist */, ); @@ -113,7 +118,7 @@ F43F829A26578DCA001D9B3D /* Scenes */ = { isa = PBXGroup; children = ( - F43F829B26578DCA001D9B3D /* RootController.swift */, + F43F829B26578DCA001D9B3D /* PresetsController.swift */, ); path = Scenes; sourceTree = ""; @@ -134,6 +139,14 @@ path = "tvOS Example"; sourceTree = ""; }; + F4B96F9A265AC36800A01A29 /* Models */ = { + isa = PBXGroup; + children = ( + F4B96F9B265AC36F00A01A29 /* IndicatorPresetModel.swift */, + ); + path = Models; + sourceTree = ""; + }; F4BAA43C2658297300DA5BF7 /* App */ = { isa = PBXGroup; children = ( @@ -164,6 +177,7 @@ packageProductDependencies = ( F4BAA4342658292F00DA5BF7 /* SparrowKit */, F4BAA4362658293600DA5BF7 /* SPIndicator */, + F4B96F98265AC34400A01A29 /* SPDiffable */, ); productName = SparrowKit; productReference = F43F827B26578D83001D9B3D /* iOS Example.app */; @@ -218,6 +232,7 @@ mainGroup = F43F827226578D83001D9B3D; packageReferences = ( F4BAA4332658292F00DA5BF7 /* XCRemoteSwiftPackageReference "SparrowKit" */, + F4B96F97265AC34400A01A29 /* XCRemoteSwiftPackageReference "SPDiffable" */, ); productRefGroup = F43F827C26578D83001D9B3D /* Products */; projectDirPath = ""; @@ -255,7 +270,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - F43F82A126578DCA001D9B3D /* RootController.swift in Sources */, + F43F82A126578DCA001D9B3D /* PresetsController.swift in Sources */, + F4B96F9C265AC36F00A01A29 /* IndicatorPresetModel.swift in Sources */, F43F829F26578DCA001D9B3D /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -404,14 +420,14 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = ""; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = T9Z76HLJ3T; + DEVELOPMENT_TEAM = NPYZ6A48AA; INFOPLIST_FILE = "iOS Example/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 12.1; + IPHONEOS_DEPLOYMENT_TARGET = 14.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = by.ivanvorobei.sparrowkit.ios; + PRODUCT_BUNDLE_IDENTIFIER = by.ivanvorobei.spperspective; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -424,14 +440,14 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = ""; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = T9Z76HLJ3T; + DEVELOPMENT_TEAM = NPYZ6A48AA; INFOPLIST_FILE = "iOS Example/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 12.1; + IPHONEOS_DEPLOYMENT_TARGET = 14.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = by.ivanvorobei.sparrowkit.ios; + PRODUCT_BUNDLE_IDENTIFIER = by.ivanvorobei.spperspective; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -513,6 +529,14 @@ /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ + F4B96F97265AC34400A01A29 /* XCRemoteSwiftPackageReference "SPDiffable" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/ivanvorobei/SPDiffable"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.2.4; + }; + }; F4BAA4332658292F00DA5BF7 /* XCRemoteSwiftPackageReference "SparrowKit" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/ivanvorobei/SparrowKit"; @@ -524,6 +548,11 @@ /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ + F4B96F98265AC34400A01A29 /* SPDiffable */ = { + isa = XCSwiftPackageProductDependency; + package = F4B96F97265AC34400A01A29 /* XCRemoteSwiftPackageReference "SPDiffable" */; + productName = SPDiffable; + }; F4BAA4342658292F00DA5BF7 /* SparrowKit */ = { isa = XCSwiftPackageProductDependency; package = F4BAA4332658292F00DA5BF7 /* XCRemoteSwiftPackageReference "SparrowKit" */; diff --git a/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 19ef864..919434a 100644 --- a/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> diff --git a/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 9cc6606..3635017 100644 --- a/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -9,6 +9,15 @@ "revision": "fe41eb5dfeab866eaecb414c352fef9e4dd95f3b", "version": "3.0.8" } + }, + { + "package": "SPDiffable", + "repositoryURL": "https://github.com/ivanvorobei/SPDiffable", + "state": { + "branch": null, + "revision": "3136eaab42a982bf28ed7f9d004304c90ffa8ad8", + "version": "1.2.4" + } } ] }, diff --git a/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcuserdata/ivanvorobei.xcuserdatad/UserInterfaceState.xcuserstate b/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcuserdata/ivanvorobei.xcuserdatad/UserInterfaceState.xcuserstate index 712ce5e..0bd3201 100644 Binary files a/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcuserdata/ivanvorobei.xcuserdatad/UserInterfaceState.xcuserstate and b/Example Apps/SPIndicator.xcodeproj/project.xcworkspace/xcuserdata/ivanvorobei.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Example Apps/iOS Example/App/AppDelegate.swift b/Example Apps/iOS Example/App/AppDelegate.swift index 42a90c7..8d6241f 100644 --- a/Example Apps/iOS Example/App/AppDelegate.swift +++ b/Example Apps/iOS Example/App/AppDelegate.swift @@ -1,5 +1,5 @@ // The MIT License (MIT) -// Copyright © 2020 Ivan Vorobei (hello@ivanvorobei.by) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -26,7 +26,7 @@ import SparrowKit class AppDelegate: SPAppWindowDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - let rootController = RootController().wrapToNavigationController(prefersLargeTitles: false) + let rootController = PresetsController().wrapToNavigationController(prefersLargeTitles: false) makeKeyAndVisible(rootController, tint: .systemBlue) return true } diff --git a/Example Apps/iOS Example/Models/IndicatorPresetModel.swift b/Example Apps/iOS Example/Models/IndicatorPresetModel.swift new file mode 100644 index 0000000..4e2bc41 --- /dev/null +++ b/Example Apps/iOS Example/Models/IndicatorPresetModel.swift @@ -0,0 +1,38 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit +import SPIndicator + +/** + Example wrapper model. + */ +struct IndicatorPresetModel { + + var name: String + var title: String + var message: String? + var preset: SPIndicatorIconPreset + + var id: String { + return name + } +} diff --git a/Example Apps/iOS Example/Scenes/PresetsController.swift b/Example Apps/iOS Example/Scenes/PresetsController.swift new file mode 100644 index 0000000..1dbed46 --- /dev/null +++ b/Example Apps/iOS Example/Scenes/PresetsController.swift @@ -0,0 +1,130 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit +import SparrowKit +import SPDiffable +import SPIndicator + +class PresetsController: SPDiffableTableController { + + // MARK: - Init + + init() { + super.init(style: .insetGrouped) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - Lifecycle + + override func viewDidLoad() { + super.viewDidLoad() + navigationItem.title = "SPAlert Presets" + + currentPreset = presets.first! + setCellProviders(SPDiffableTableCellProviders.default, sections: content) + + navigationController?.isToolbarHidden = false + toolbarItems = [ + .init(image: .system("chevron.down.circle"), primaryAction: .init(handler: { (action) in + guard let currentPreset = self.currentPreset else { + self.currentPreset = self.presets.first + return + } + guard let index = self.presets.firstIndex(where: { $0.id == currentPreset.id }) else { return } + self.currentPreset = self.presets[safe: index + 1] + if self.currentPreset == nil { + self.currentPreset = self.presets.first + } + })), + .init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + .init(systemItem: .play, primaryAction: .init(handler: { [weak self] (action) in + guard let preset = self?.currentPreset else { return } + SPIndicator.present(title: preset.title, message: preset.message, preset: preset.preset, completion: nil) + }), menu: nil), + .init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + ] + } + + // MARK: - Data + + fileprivate var presets: [IndicatorPresetModel] { + return [ + IndicatorPresetModel( + name: "Done", + title: "Done", + message: "Animatable", + preset: .done + ), + IndicatorPresetModel( + name: "Error", + title: "Oops", + message: "Try again", + preset: .error + ), + IndicatorPresetModel( + name: "Custom Image", + title: "Custom Image", + message: "SFSymbols Image", + preset: .custom(UIImage.init(systemName: "swift")!) + ), + IndicatorPresetModel( + name: "Specific Tint", + title: "Specific Tint", + message: "For any image", + preset: .custom(UIImage.init(systemName: "sun.min.fill")!.withTintColor(.systemYellow, renderingMode: .alwaysOriginal)) + ), + ] + } + + // MARK: - Diffable + + var currentPreset: IndicatorPresetModel? { + willSet { + guard let id = self.currentPreset?.id else { return } + let cell = diffableDataSource?.cell(UITableViewCell.self, for: id) + cell?.accessoryType = .none + } + didSet { + guard let id = self.currentPreset?.id else { return } + let cell = diffableDataSource?.cell(UITableViewCell.self, for: id) + cell?.accessoryType = .checkmark + } + } + + var content: [SPDiffableSection] { + let items = presets.map { (preset) -> SPDiffableTableRow in + return SPDiffableTableRow( + text: preset.name, + accessoryType: (preset.id == currentPreset?.id) ? .checkmark : .none, + selectionStyle: .none) { [weak self] _ in + guard let self = self else { return } + self.currentPreset = preset + } + } + return [ + SPDiffableSection(identifier: "presets", header: nil, footer: nil, items: items) + ] + } +} diff --git a/README.md b/README.md index b3b69ac..e0cf67f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # SPIndicator + + Floating indicator, mimicrate to indicator which appear when silent mode turn on / off. Support large texts. If you like the project, don't forget to `put star ★` and follow me on GitHub: diff --git a/Sources/SPIndicator/Extensions/UIApplicationExtension.swift b/Sources/SPIndicator/Extensions/UIApplicationExtension.swift new file mode 100644 index 0000000..5468ba5 --- /dev/null +++ b/Sources/SPIndicator/Extensions/UIApplicationExtension.swift @@ -0,0 +1,29 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +extension UIApplication { + + var userInterfaceRightToLeft: Bool { + UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft + } +} diff --git a/Sources/SPIndicator/Extensions/UIColorExtension.swift b/Sources/SPIndicator/Extensions/UIColorExtension.swift new file mode 100644 index 0000000..f37e221 --- /dev/null +++ b/Sources/SPIndicator/Extensions/UIColorExtension.swift @@ -0,0 +1,92 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +extension UIColor { + + enum Compability { + + static var systemBackground: UIColor { + #if os(iOS) + if #available(iOS 13.0, *) { + return UIColor.systemBackground + } + #endif + return UIColor.white + } + + static var secondarySystemBackground: UIColor { + #if os(iOS) + if #available(iOS 13.0, *) { + return UIColor.secondarySystemBackground + } + #endif + return UIColor(red: 242/255, green: 242/255, blue: 247/255, alpha: 1) + } + + static var separator: UIColor { + if #available(iOS 13.0, tvOS 13.0, *) { + return UIColor.separator + } else { + return UIColor(red: 60/255, green: 60/255, blue: 67/255, alpha: 1) + } + } + + static var label: UIColor { + if #available(iOS 13.0, tvOS 13.0, *) { + return UIColor.label + } else { + return UIColor.black + } + } + + static var secondaryLabel: UIColor { + if #available(iOS 13.0, tvOS 13.0, *) { + return UIColor.secondaryLabel + } else { + return UIColor(red: 138/255, green: 138/255, blue: 142/255, alpha: 1) + } + } + } + + static var buttonArea: UIColor { + if #available(iOS 13.0, tvOS 13.0, *) { + return UIColor { (traits) -> UIColor in + return traits.userInterfaceStyle == .dark ? UIColor(red: 61/255, green: 62/255, blue: 66/255, alpha: 1) : + UIColor(red: 238/255, green: 238/255, blue: 240/255, alpha: 1) + } + } else { + return UIColor(red: 238/255, green: 238/255, blue: 240/255, alpha: 1) + } + } + + static var tint: UIColor { + get { + let value = UIApplication.shared.windows.first?.tintColor + guard let tint = value else { return .systemBlue } + return tint + } + set { + UIApplication.shared.windows.forEach({ $0.tintColor = newValue }) + } + } +} diff --git a/Sources/SPIndicator/Extensions/UIFontExtension.swift b/Sources/SPIndicator/Extensions/UIFontExtension.swift new file mode 100644 index 0000000..688bcc3 --- /dev/null +++ b/Sources/SPIndicator/Extensions/UIFontExtension.swift @@ -0,0 +1,32 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +extension UIFont { + + static func preferredFont(forTextStyle style: TextStyle, weight: Weight, addPoints: CGFloat = 0) -> UIFont { + let descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style) + let font = UIFont.systemFont(ofSize: descriptor.pointSize + addPoints, weight: weight) + let metrics = UIFontMetrics(forTextStyle: style) + return metrics.scaledFont(for: font) + } +} diff --git a/Sources/SPIndicator/Extensions/UILabelExtension.swift b/Sources/SPIndicator/Extensions/UILabelExtension.swift new file mode 100644 index 0000000..2443dbe --- /dev/null +++ b/Sources/SPIndicator/Extensions/UILabelExtension.swift @@ -0,0 +1,37 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +extension UILabel { + + func layoutDynamicHeight(width: CGFloat) { + layoutDynamicHeight(x: frame.origin.x, y: frame.origin.y, width: width) + } + + func layoutDynamicHeight(x: CGFloat, y: CGFloat, width: CGFloat) { + frame = CGRect.init(x: x, y: y, width: width, height: frame.height) + sizeToFit() + if frame.width != width { + frame = .init(x: x, y: y, width: width, height: frame.height) + } + } +} diff --git a/Sources/SPIndicator/Icons/SPAlertIconErrorView.swift b/Sources/SPIndicator/Icons/SPAlertIconErrorView.swift new file mode 100644 index 0000000..46bf1e1 --- /dev/null +++ b/Sources/SPIndicator/Icons/SPAlertIconErrorView.swift @@ -0,0 +1,84 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +public class SPIndicatorIconErrorView: UIView, SPIndicatorIconAnimatable { + + public func animate() { + animateTopToBottomLine() + animateBottomToTopLine() + } + + private func animateTopToBottomLine() { + let length = frame.width + + let topToBottomLine = UIBezierPath() + topToBottomLine.move(to: CGPoint(x: length * 0, y: length * 0)) + topToBottomLine.addLine(to: CGPoint(x: length * 1, y: length * 1)) + + let animatableLayer = CAShapeLayer() + animatableLayer.path = topToBottomLine.cgPath + animatableLayer.fillColor = UIColor.clear.cgColor + animatableLayer.strokeColor = tintColor?.cgColor + animatableLayer.lineWidth = 4 + animatableLayer.lineCap = .round + animatableLayer.lineJoin = .round + animatableLayer.strokeEnd = 0 + self.layer.addSublayer(animatableLayer) + + let animation = CABasicAnimation(keyPath: "strokeEnd") + animation.duration = 0.22 + animation.fromValue = 0 + animation.toValue = 1 + animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + + animatableLayer.strokeEnd = 1 + animatableLayer.add(animation, forKey: "animation") + } + + private func animateBottomToTopLine() { + let length = frame.width + + let bottomToTopLine = UIBezierPath() + bottomToTopLine.move(to: CGPoint(x: length * 0, y: length * 1)) + bottomToTopLine.addLine(to: CGPoint(x: length * 1, y: length * 0)) + + let animatableLayer = CAShapeLayer() + animatableLayer.path = bottomToTopLine.cgPath + animatableLayer.fillColor = UIColor.clear.cgColor + animatableLayer.strokeColor = tintColor?.cgColor + animatableLayer.lineWidth = 4 + animatableLayer.lineCap = .round + animatableLayer.lineJoin = .round + animatableLayer.strokeEnd = 0 + self.layer.addSublayer(animatableLayer) + + let animation = CABasicAnimation(keyPath: "strokeEnd") + animation.duration = 0.22 + animation.fromValue = 0 + animation.toValue = 1 + animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + + animatableLayer.strokeEnd = 1 + animatableLayer.add(animation, forKey: "animation") + } +} diff --git a/Sources/SPIndicator/Icons/SPIndicatorIconDoneView.swift b/Sources/SPIndicator/Icons/SPIndicatorIconDoneView.swift new file mode 100644 index 0000000..22a8632 --- /dev/null +++ b/Sources/SPIndicator/Icons/SPIndicatorIconDoneView.swift @@ -0,0 +1,51 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +public class SPIndicatorIconDoneView: UIView, SPIndicatorIconAnimatable { + + public func animate() { + let length = frame.width + let animatablePath = UIBezierPath() + animatablePath.move(to: CGPoint(x: length * 0.196, y: length * 0.527)) + animatablePath.addLine(to: CGPoint(x: length * 0.47, y: length * 0.777)) + animatablePath.addLine(to: CGPoint(x: length * 0.99, y: length * 0.25)) + + let animatableLayer = CAShapeLayer() + animatableLayer.path = animatablePath.cgPath + animatableLayer.fillColor = UIColor.clear.cgColor + animatableLayer.strokeColor = tintColor?.cgColor + animatableLayer.lineWidth = 4 + animatableLayer.lineCap = .round + animatableLayer.lineJoin = .round + animatableLayer.strokeEnd = 0 + layer.addSublayer(animatableLayer) + + let animation = CABasicAnimation(keyPath: "strokeEnd") + animation.duration = 0.25 + animation.fromValue = 0 + animation.toValue = 1 + animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + animatableLayer.strokeEnd = 1 + animatableLayer.add(animation, forKey: "animation") + } +} diff --git a/Sources/SPIndicator/Models/SPIndicatorLayout.swift b/Sources/SPIndicator/Models/SPIndicatorLayout.swift new file mode 100644 index 0000000..3b1fcae --- /dev/null +++ b/Sources/SPIndicator/Models/SPIndicatorLayout.swift @@ -0,0 +1,40 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +open class SPIndicatorLayout { + + /** + SPIndicator: Icon size. + */ + open var iconSize: CGSize + + /** + SPIndicator: Alert margings for each side. + */ + open var margins: UIEdgeInsets + + public init(iconSize: CGSize, margins: UIEdgeInsets) { + self.iconSize = iconSize + self.margins = margins + } +} diff --git a/Example Apps/iOS Example/Scenes/RootController.swift b/Sources/SPIndicator/Protocols/SPIndicatorIconAnimatable.swift similarity index 89% rename from Example Apps/iOS Example/Scenes/RootController.swift rename to Sources/SPIndicator/Protocols/SPIndicatorIconAnimatable.swift index 54f8dad..10a0ffe 100644 --- a/Example Apps/iOS Example/Scenes/RootController.swift +++ b/Sources/SPIndicator/Protocols/SPIndicatorIconAnimatable.swift @@ -1,5 +1,5 @@ // The MIT License (MIT) -// Copyright © 2020 Ivan Vorobei (hello@ivanvorobei.by) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,6 +20,8 @@ // SOFTWARE. import UIKit -import SparrowKit -class RootController: SPController {} +public protocol SPIndicatorIconAnimatable { + + func animate() +} diff --git a/Sources/SPIndicator/SPIndicator.swift b/Sources/SPIndicator/SPIndicator.swift index 0ce4b4f..6ff77d4 100644 --- a/Sources/SPIndicator/SPIndicator.swift +++ b/Sources/SPIndicator/SPIndicator.swift @@ -1,3 +1,69 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + import UIKit -enum SPIndicator {} +public enum SPIndicator { + + #if os(iOS) + + /** + SPIndicator: Present alert with preset and custom haptic. + + - parameter title: Title text in alert. + - parameter message: Subtitle text in alert. Optional. + - parameter preset: Icon ready-use style or custom image. + - parameter haptic: Haptic response with present. Default is `.success`. + - parameter completion: Will call with dismiss alert. + */ + public static func present(title: String, message: String? = nil, preset: SPIndicatorIconPreset, haptic: SPIndicatorHaptic, completion: (() -> Void)? = nil) { + let alertView = SPIndicatorView(title: title, message: message, preset: preset) + alertView.present(haptic: haptic, completion: completion) + } + + /** + SPIndicator: Present alert with preset and automatically detect type haptic. + + - parameter title: Title text in alert. + - parameter message: Subtitle text in alert. Optional. + - parameter preset: Icon ready-use style or custom image. + - parameter completion: Will call with dismiss alert. + */ + public static func present(title: String, message: String? = nil, preset: SPIndicatorIconPreset, completion: (() -> Void)? = nil) { + let alertView = SPIndicatorView(title: title, message: message, preset: preset) + let haptic = preset.getHaptic() + alertView.present(haptic: haptic, completion: completion) + } + + /** + SPIndicator: Show only message, without title and icon. + + - parameter message: Title text. + - parameter haptic: Haptic response with present. Default is `.success`. + - parameter completion: Will call with dismiss alert. + */ + public static func present(message: String, haptic: SPIndicatorHaptic, completion: (() -> Void)? = nil) { + let alertView = SPIndicatorView(message: message) + alertView.present(haptic: haptic, completion: completion) + } + + #endif +} diff --git a/Sources/SPIndicator/SPIndicatorIconPreset.swift b/Sources/SPIndicator/SPIndicatorIconPreset.swift new file mode 100644 index 0000000..124c12f --- /dev/null +++ b/Sources/SPIndicator/SPIndicatorIconPreset.swift @@ -0,0 +1,105 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +public enum SPIndicatorIconPreset { + + case done + case error + + case custom(_ image: UIImage) +} + +// Get view and haptic by Preset. + +public extension SPIndicatorIconPreset { + + func createView() -> UIView { + switch self { + case .done: + let view = SPIndicatorIconDoneView() + return view + case .error: + let view = SPIndicatorIconErrorView() + view.tintColor = UIColor.systemRed + return view + case .custom(let image): + let imageView = UIImageView(image: image) + imageView.contentMode = .scaleAspectFit + return imageView + } + } + + func getHaptic() -> SPIndicatorHaptic { + switch self { + case .error: return .error + case .done: return .success + case .custom(_): return .none + } + } +} + +// Get layout by preset. + +public extension SPIndicatorLayout { + + convenience init() { + self.init( + iconSize: .init( + width: Self.defaultIconSideSize, + height: Self.defaultIconSideSize + ), + margins: .init( + top: Self.defaultVerticallInset, + left: Self.defaultHorizontalInset, + bottom: Self.defaultVerticallInset, + right: Self.defaultHorizontalInset + ) + ) + } + + static func message() -> SPIndicatorLayout { + let layout = SPIndicatorLayout() + return layout + } + + convenience init(for preset: SPIndicatorIconPreset) { + switch preset { + case .done: + self.init() + iconSize = .init(width: 24, height: 24) + case .error: + self.init() + iconSize = .init(width: 14, height: 14) + margins.left = 19 + margins.right = margins.left + case .custom(_): + self.init() + } + } + + private static var defaultIconSideSize: CGFloat { 28 } + private static var defaultSpaceBetweenIconAndTitle: CGFloat { 26 } + private static var defaultVerticallInset: CGFloat { 8 } + private static var defaultHorizontalInset: CGFloat { 15 } +} + diff --git a/Sources/SPIndicator/SPIndicatorView.swift b/Sources/SPIndicator/SPIndicatorView.swift new file mode 100644 index 0000000..e01d1bb --- /dev/null +++ b/Sources/SPIndicator/SPIndicatorView.swift @@ -0,0 +1,295 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +#if os(iOS) + +class SPIndicatorView: UIView { + + // MARK: - Properties + + open var dismissByTap: Bool = true + open var completion: (() -> Void)? = nil + + // MARK: - Views + + open var titleLabel: UILabel? + open var subtitleLabel: UILabel? + open var iconView: UIView? + + private lazy var backgroundView: UIVisualEffectView = { + let view: UIVisualEffectView = { + if #available(iOS 13.0, *) { + return UIVisualEffectView(effect: UIBlurEffect(style: .systemThickMaterial)) + } else { + return UIVisualEffectView(effect: UIBlurEffect(style: .light)) + } + }() + view.isUserInteractionEnabled = false + return view + }() + + weak open var presentWindow: UIWindow? = UIApplication.shared.windows.first + + // MARK: - Init + + public init(title: String, message: String? = nil, preset: SPIndicatorIconPreset) { + super.init(frame: CGRect.zero) + commonInit() + layout = SPIndicatorLayout(for: preset) + setTitle(title) + if let message = message { + setMessage(message) + } + setIcon(for: preset) + } + + public init(message: String) { + super.init(frame: CGRect.zero) + commonInit() + layout = SPIndicatorLayout.message() + setMessage(message) + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + commonInit() + } + + private func commonInit() { + preservesSuperviewLayoutMargins = false + if #available(iOS 11.0, *) { + insetsLayoutMarginsFromSafeArea = false + } + + backgroundColor = .clear + backgroundView.layer.masksToBounds = true + addSubview(backgroundView) + + updateShadow() + } + + // MARK: - Configure + + private func setTitle(_ text: String) { + let label = UILabel() + label.font = UIFont.preferredFont(forTextStyle: .footnote, weight: .semibold, addPoints: 0) + label.numberOfLines = 1 + let style = NSMutableParagraphStyle() + style.lineBreakMode = .byTruncatingTail + style.lineSpacing = 3 + label.attributedText = NSAttributedString( + string: text, attributes: [.paragraphStyle: style] + ) + label.textAlignment = .center + label.textColor = UIColor.Compability.label.withAlphaComponent(0.5) + titleLabel = label + addSubview(label) + } + + private func setMessage(_ text: String) { + let label = UILabel() + label.font = UIFont.preferredFont(forTextStyle: .footnote, weight: .semibold, addPoints: 0) + label.numberOfLines = 1 + let style = NSMutableParagraphStyle() + style.lineBreakMode = .byTruncatingTail + style.lineSpacing = 2 + label.attributedText = NSAttributedString( + string: text, attributes: [.paragraphStyle: style] + ) + label.textAlignment = .center + label.textColor = UIColor.Compability.label.withAlphaComponent(0.2) + subtitleLabel = label + addSubview(label) + } + + private func setIcon(for preset: SPIndicatorIconPreset) { + let view = preset.createView() + self.iconView = view + addSubview(view) + } + + private func updateShadow() { + layer.shadowColor = UIColor.black.cgColor + layer.shadowOpacity = 0.22 + layer.shadowOffset = .init(width: 0, height: 7) + layer.shadowRadius = 40 + + // Not use render shadow becouse backgorund is visual effect. + // If turn on it, background will hide. + // layer.shouldRasterize = true + } + + // MARK: - Layout + + open var layout: SPIndicatorLayout = .init() + + private var areaHeight: CGFloat = 50 + private var minimumAreaWidth: CGFloat = 196 + private var maximumAreaWidth: CGFloat = 260 + private var spaceBetweenTitles: CGFloat = 1 + private var spaceBetweenTitlesAndImage: CGFloat = 16 + + private var titlesCompactWidth: CGFloat { + if let iconView = self.iconView { + let space = iconView.frame.maxY + spaceBetweenTitlesAndImage + return frame.width - space * 2 + } else { + return frame.width - layoutMargins.left - layoutMargins.right + } + } + + private var titlesFullWidth: CGFloat { + if let iconView = self.iconView { + let space = iconView.frame.maxY + spaceBetweenTitlesAndImage + return frame.width - space - layoutMargins.right + } else { + return frame.width - layoutMargins.left - layoutMargins.right + } + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + titleLabel?.sizeToFit() + let titleWidth: CGFloat = titleLabel?.frame.width ?? 0 + subtitleLabel?.sizeToFit() + let subtitleWidth: CGFloat = subtitleLabel?.frame.width ?? 0 + var width = (max(titleWidth, subtitleWidth) * 2.5).rounded() + + if width < minimumAreaWidth { width = minimumAreaWidth } + if width > maximumAreaWidth { width = maximumAreaWidth } + + return .init(width: width, height: areaHeight) + } + + override func layoutSubviews() { + super.layoutSubviews() + + layoutMargins = layout.margins + + layer.cornerRadius = frame.height / 2 + backgroundView.frame = bounds + backgroundView.layer.cornerRadius = layer.cornerRadius + + if let iconView = self.iconView { + iconView.frame = .init( + origin: .init(x: layoutMargins.right, y: iconView.frame.origin.y), + size: layout.iconSize + ) + iconView.center.y = bounds.midY + } + + if let titleLabel = self.titleLabel { + titleLabel.sizeToFit() + if titleLabel.frame.width > titlesCompactWidth { + titleLabel.textAlignment = UIApplication.shared.userInterfaceRightToLeft ? .right : .left + titleLabel.layoutDynamicHeight(width: titlesFullWidth) + titleLabel.frame.origin.x = layoutMargins.left + (iconView?.frame.width ?? 0) + spaceBetweenTitlesAndImage + } else { + titleLabel.textAlignment = .center + titleLabel.layoutDynamicHeight(width: titlesCompactWidth) + titleLabel.center.x = frame.width / 2 + } + } + + if let subtitleLabel = self.subtitleLabel { + subtitleLabel.sizeToFit() + if subtitleLabel.frame.width > titlesCompactWidth { + subtitleLabel.textAlignment = UIApplication.shared.userInterfaceRightToLeft ? .right : .left + subtitleLabel.layoutDynamicHeight(width: titlesFullWidth) + subtitleLabel.frame.origin.x = layoutMargins.left + (iconView?.frame.width ?? 0) + spaceBetweenTitlesAndImage + } else { + subtitleLabel.textAlignment = .center + subtitleLabel.layoutDynamicHeight(width: titlesCompactWidth) + subtitleLabel.center.x = frame.width / 2 + } + } + + if (titleLabel != nil) && (subtitleLabel == nil) { + titleLabel?.center.y = bounds.midY + } + + if (titleLabel != nil) && (subtitleLabel != nil) { + let allHeight = (titleLabel?.frame.height ?? 0) + (subtitleLabel?.frame.height ?? 0) + spaceBetweenTitles + titleLabel?.frame.origin.y = (frame.height - allHeight) / 2 + subtitleLabel?.frame.origin.y = (titleLabel?.frame.maxY ?? 0) + spaceBetweenTitles + } + } + + // MARK: - Present + + fileprivate var presentAndDismissDuration: TimeInterval = 0.6 + + fileprivate var startPresentPosition: CGFloat { + -((UIApplication.shared.windows.first?.safeAreaInsets.top ?? 0) + 50) + } + + fileprivate var endPresentPosition: CGFloat { + var topSafeAreaInsets = (UIApplication.shared.windows.first?.safeAreaInsets.top ?? 0) + if topSafeAreaInsets < 20 { topSafeAreaInsets = 20 } + return topSafeAreaInsets - 3 + } + + open func present(duration: TimeInterval = 1.5, haptic: SPIndicatorHaptic = .success, completion: (() -> Void)? = nil) { + guard let window = self.presentWindow else { return } + + window.addSubview(self) + + // Prepare for present + + self.completion = completion + + isHidden = true + sizeToFit() + layoutSubviews() + center.x = window.frame.midX + transform = CGAffineTransform.identity.translatedBy(x: 0, y: startPresentPosition) + + // Present + + isHidden = false + haptic.impact() + UIView.animate(withDuration: presentAndDismissDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState, .curveEaseOut], animations: { + self.transform = CGAffineTransform.identity.translatedBy(x: 0, y: self.endPresentPosition) + }, completion: { finished in + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { + self.dismiss() + } + }) + + if let iconView = self.iconView as? SPIndicatorIconAnimatable { + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + presentAndDismissDuration / 3) { + iconView.animate() + } + } + } + + @objc open func dismiss() { + UIView.animate(withDuration: presentAndDismissDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState, .curveEaseIn], animations: { + self.transform = CGAffineTransform.identity.translatedBy(x: 0, y: self.startPresentPosition) + }, completion: { finished in + self.removeFromSuperview() + self.completion?() + }) + } +} + +#endif diff --git a/Sources/SPIndicator/Services/SPIndicatorHaptic.swift b/Sources/SPIndicator/Services/SPIndicatorHaptic.swift new file mode 100644 index 0000000..cbc7862 --- /dev/null +++ b/Sources/SPIndicator/Services/SPIndicatorHaptic.swift @@ -0,0 +1,48 @@ +// The MIT License (MIT) +// Copyright © 2021 Ivan Vorobei (hello@ivanvorobei.by) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import UIKit + +public enum SPIndicatorHaptic { + + case success + case warning + case error + case none + + func impact() { + #if os(iOS) + let generator = UINotificationFeedbackGenerator() + switch self { + case .success: + generator.notificationOccurred(UINotificationFeedbackGenerator.FeedbackType.success) + case .warning: + generator.notificationOccurred(UINotificationFeedbackGenerator.FeedbackType.warning) + case .error: + generator.notificationOccurred(UINotificationFeedbackGenerator.FeedbackType.error) + case .none: + break + } + #endif + } +} + + diff --git a/TODO.md b/TODO.md index f3d6db6..ce2bc61 100644 --- a/TODO.md +++ b/TODO.md @@ -1,3 +1,9 @@ # TODO Here provided ideas or features which will be implemented soon. + +- Gester for hide +- Documentations +- Add grades for left and right side when text not fit, including scroll animation for label +- Add tvOS version (left-top corner) +- Add tvOS docs