diff --git a/Podfile b/Podfile new file mode 100644 index 00000000..7c7925d7 --- /dev/null +++ b/Podfile @@ -0,0 +1,120 @@ +# Uncomment the next line to define a global platform for your project +source 'https://gitee.com/mirrors/CocoaPods-Specs.git' +platform :ios, '15.0' + +target 'QuickLocation' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for QuickLocation + # Pods for Base + pod 'Moya' + pod 'ObjectMapper' + pod 'RxCocoa' + pod 'RxSwift' + pod 'SwiftyUserDefaults' + pod 'SwiftyJSON' + pod 'URLNavigator' + pod 'RxDataSources' + pod 'RxSwiftExt' + pod 'SwiftDate' + #pod 'RxGesture' + pod 'CocoaLumberjack/Swift' + pod 'KingfisherWebP' + pod 'Masonry' + + #工具 + #pod 'FLEX', :configurations => ['Debug', 'AdHoc'] + pod 'HXPHPicker' + pod 'SwiftKeychainWrapper' + pod 'SGQRCode', '~> 4.1.0' #扫描 + #pod 'PGDatePicker' + pod 'IQKeyboardManagerSwift' + + #UI + pod 'SnapKit' + pod 'MJRefresh' + pod 'MBProgressHUD', :git => 'https://github.com/jdg/MBProgressHUD.git' + pod 'MarqueeLabel' + pod 'Popover' + + #第三方SDk + pod 'GYSDK' #个推一键登录 + + #高德地图 + pod 'AMap3DMap' #3D地图SDK + pod 'AMapSearch' #地图SDK搜索功能 + pod 'AMapLocation' #定位SDK + +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0' + end + end + + # These frameworks ship without a valid arm64-simulator slice (even some + # xcframeworks contain device-only arm64). Linking them for simulator on + # Xcode 15+ (arm64-only simulator) fails. Fix: remove EXCLUDED_ARCHS (so + # simulator destinations appear), strip them from general OTHER_LDFLAGS, + # and add them back only via OTHER_LDFLAGS[sdk=iphoneos*]. + device_only_fws = %w[MAMapKit AMapFoundationKit AMapLocationKit AMapSearchKit ZXSDK GeYanSdk GTCommonSDK] + device_only_dirs = %w[AMap3DMap AMapFoundation AMapLocation AMapSearch ZXSDK GYSDK GTCommonSDK] + + Dir.glob(File.join(installer.sandbox.root, 'Target Support Files', '**', '*.xcconfig')).each do |path| + content = File.read(path) + + # Remove arm64 exclusion + content.gsub!(/^EXCLUDED_ARCHS\[sdk=iphonesimulator\*\] = arm64.*\n?/, '') + + if content =~ /^OTHER_LDFLAGS = (.+)$/ + ldflags = $1 + stripped_ld = false + + device_only_fws.each do |fw| + if ldflags.gsub!(/ *-(weak_)?framework "#{fw}"/, '') + stripped_ld = true + end + end + + content.sub!(/^OTHER_LDFLAGS = .+$/, "OTHER_LDFLAGS = #{ldflags}") + + # Remove any old conditional lines + content.gsub!(/^OTHER_LDFLAGS\[sdk=iphonesimulator\*\].*\n?/, '') + content.gsub!(/^OTHER_LDFLAGS\[sdk=iphoneos\*\].*\n?/, '') + + # Only add device-only conditional if we actually stripped something + if stripped_ld + device_flags = device_only_fws.map { |fw| %(-framework "#{fw}") }.join(' ') + content += "\nOTHER_LDFLAGS[sdk=iphoneos*] = $(inherited) #{device_flags}\n" + end + end + + # Strip device-only dirs from FRAMEWORK_SEARCH_PATHS and move to iphoneos only + if content =~ /^FRAMEWORK_SEARCH_PATHS = (.+)$/ + fsp = $1 + device_search_paths = [] + + device_only_dirs.each do |dir| + %w[PODS_ROOT PODS_CONFIGURATION_BUILD_DIR PODS_XCFRAMEWORKS_BUILD_DIR].each do |var| + pattern = / *"\$\{#{var}\}\/#{dir}"/ + if fsp.match?(pattern) + fsp.gsub!(pattern, '') + device_search_paths << "\"${#{var}}/#{dir}\"" + end + end + end + + content.sub!(/^FRAMEWORK_SEARCH_PATHS = .+$/, "FRAMEWORK_SEARCH_PATHS = #{fsp}") + content.gsub!(/^FRAMEWORK_SEARCH_PATHS\[sdk=iphoneos\*\].*\n?/, '') + + unless device_search_paths.empty? + content += "\nFRAMEWORK_SEARCH_PATHS[sdk=iphoneos*] = $(inherited) #{device_search_paths.uniq.join(' ')}\n" + end + end + + File.write(path, content) + end +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 00000000..08815247 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,243 @@ +PODS: + - Alamofire (5.10.1) + - AMap3DMap (11.1.200): + - AMapFoundation (>= 1.8.7) + - AMapFoundation (1.8.7) + - AMapLocation (2.11.1): + - AMapFoundation (>= 1.8.7) + - AMapSearch (9.7.5): + - AMapFoundation (>= 1.8.0) + - CocoaLumberjack/Core (3.9.1) + - CocoaLumberjack/Swift (3.9.1): + - CocoaLumberjack/Core + - Differentiator (5.0.0) + - GTCommonSDK (3.2.3.0): + - ZXSDK + - GYSDK (3.1.3.0): + - GTCommonSDK (>= 3.0.0.0) + - HXPHPicker (1.1.5): + - HXPHPicker/Core (= 1.1.5) + - HXPHPicker/Editor (= 1.1.5) + - HXPHPicker/Picker (= 1.1.5) + - HXPHPicker/Core (1.1.5) + - HXPHPicker/Editor (1.1.5): + - HXPHPicker/Core + - HXPHPicker/Picker (1.1.5): + - HXPHPicker/Core + - IQKeyboardCore (1.0.8) + - IQKeyboardManagerSwift (8.0.1): + - IQKeyboardManagerSwift/Appearance (= 8.0.1) + - IQKeyboardManagerSwift/Core (= 8.0.1) + - IQKeyboardManagerSwift/IQKeyboardReturnManager (= 8.0.1) + - IQKeyboardManagerSwift/IQKeyboardToolbarManager (= 8.0.1) + - IQKeyboardManagerSwift/IQTextView (= 8.0.1) + - IQKeyboardManagerSwift/Resign (= 8.0.1) + - IQKeyboardManagerSwift/Appearance (8.0.1): + - IQKeyboardManagerSwift/Core + - IQKeyboardManagerSwift/Core (8.0.1): + - IQKeyboardNotification + - IQTextInputViewNotification + - IQKeyboardManagerSwift/IQKeyboardReturnManager (8.0.1): + - IQKeyboardReturnManager + - IQKeyboardManagerSwift/IQKeyboardToolbarManager (8.0.1): + - IQKeyboardManagerSwift/Core + - IQKeyboardToolbarManager + - IQKeyboardManagerSwift/IQTextView (8.0.1): + - IQTextView + - IQKeyboardManagerSwift/Resign (8.0.1): + - IQKeyboardManagerSwift/Core + - IQKeyboardNotification (1.0.6) + - IQKeyboardReturnManager (1.0.6): + - IQKeyboardCore + - IQKeyboardToolbar (1.1.3): + - IQKeyboardToolbar/Core (= 1.1.3) + - IQKeyboardToolbar/Core (1.1.3): + - IQKeyboardCore + - IQKeyboardToolbar/Placeholderable + - IQKeyboardToolbar/Placeholderable (1.1.3) + - IQKeyboardToolbarManager (1.1.5): + - IQKeyboardToolbar + - IQTextInputViewNotification + - IQTextInputViewNotification (1.0.9): + - IQKeyboardCore + - IQTextView (1.0.5): + - IQKeyboardToolbar/Placeholderable + - Kingfisher (8.1.1) + - KingfisherWebP (1.7.3): + - Kingfisher (~> 8.0) + - libwebp (>= 1.1.0) + - libwebp (1.5.0): + - libwebp/demux (= 1.5.0) + - libwebp/mux (= 1.5.0) + - libwebp/sharpyuv (= 1.5.0) + - libwebp/webp (= 1.5.0) + - libwebp/demux (1.5.0): + - libwebp/webp + - libwebp/mux (1.5.0): + - libwebp/demux + - libwebp/sharpyuv (1.5.0) + - libwebp/webp (1.5.0): + - libwebp/sharpyuv + - MarqueeLabel (4.5.3) + - Masonry (1.1.0) + - MBProgressHUD (1.2.0) + - MJRefresh (3.7.9) + - Moya (15.0.0): + - Moya/Core (= 15.0.0) + - Moya/Core (15.0.0): + - Alamofire (~> 5.0) + - ObjectMapper (4.4.2) + - Popover (1.3.0) + - RxCocoa (6.8.0): + - RxRelay (= 6.8.0) + - RxSwift (= 6.8.0) + - RxDataSources (5.0.0): + - Differentiator (~> 5.0) + - RxCocoa (~> 6.0) + - RxSwift (~> 6.0) + - RxRelay (6.8.0): + - RxSwift (= 6.8.0) + - RxSwift (6.8.0) + - RxSwiftExt (6.2.1): + - RxSwiftExt/Core (= 6.2.1) + - RxSwiftExt/RxCocoa (= 6.2.1) + - RxSwiftExt/Core (6.2.1): + - RxSwift (~> 6.0) + - RxSwiftExt/RxCocoa (6.2.1): + - RxCocoa (~> 6.0) + - RxSwiftExt/Core + - SGQRCode (4.1.0) + - SnapKit (5.7.1) + - SwiftDate (7.0.0) + - SwiftKeychainWrapper (4.0.1) + - SwiftyJSON (5.0.2) + - SwiftyUserDefaults (5.3.0) + - URLNavigator (2.5.1) + - ZXSDK (3.3.2) + +DEPENDENCIES: + - AMap3DMap + - AMapLocation + - AMapSearch + - CocoaLumberjack/Swift + - GYSDK + - HXPHPicker + - IQKeyboardManagerSwift + - KingfisherWebP + - MarqueeLabel + - Masonry + - MBProgressHUD (from `https://github.com/jdg/MBProgressHUD.git`) + - MJRefresh + - Moya + - ObjectMapper + - Popover + - RxCocoa + - RxDataSources + - RxSwift + - RxSwiftExt + - SGQRCode (~> 4.1.0) + - SnapKit + - SwiftDate + - SwiftKeychainWrapper + - SwiftyJSON + - SwiftyUserDefaults + - URLNavigator + +SPEC REPOS: + https://gitee.com/mirrors/CocoaPods-Specs.git: + - Alamofire + - AMap3DMap + - AMapFoundation + - AMapLocation + - AMapSearch + - CocoaLumberjack + - Differentiator + - GTCommonSDK + - GYSDK + - HXPHPicker + - IQKeyboardCore + - IQKeyboardManagerSwift + - IQKeyboardNotification + - IQKeyboardReturnManager + - IQKeyboardToolbar + - IQKeyboardToolbarManager + - IQTextInputViewNotification + - IQTextView + - Kingfisher + - KingfisherWebP + - libwebp + - MarqueeLabel + - Masonry + - MJRefresh + - Moya + - ObjectMapper + - Popover + - RxCocoa + - RxDataSources + - RxRelay + - RxSwift + - RxSwiftExt + - SGQRCode + - SnapKit + - SwiftDate + - SwiftKeychainWrapper + - SwiftyJSON + - SwiftyUserDefaults + - URLNavigator + - ZXSDK + +EXTERNAL SOURCES: + MBProgressHUD: + :git: https://github.com/jdg/MBProgressHUD.git + +CHECKOUT OPTIONS: + MBProgressHUD: + :commit: 4a7c5f3e53cdea77c5dcb8578c2ee5acacdf6781 + :git: https://github.com/jdg/MBProgressHUD.git + +SPEC CHECKSUMS: + Alamofire: 840d2a1ad82355b536ec6ba5f97e5bfa54600ca3 + AMap3DMap: 89c17fdbca2f25e4b46d6a45a8e50346980fc799 + AMapFoundation: e99da1cc722528c60b39340b4763a95305f6c55e + AMapLocation: 6e44f50b044dc54c6b3dcb1dee5ffd6de2689e41 + AMapSearch: 29224a399b56b17da1540e4312fc4d9dc37342bb + CocoaLumberjack: e4ba3b414dfca8c1916c6303d37f63b3a95134c6 + Differentiator: e8497ceab83c1b10ca233716d547b9af21b9344d + GTCommonSDK: 238c6735add91e654f8564638854686ee3dcb4ac + GYSDK: db5f4b3aae8df06201be5e786076211ec11791be + HXPHPicker: 451f6af62845d60d5dd2235f4665d81f2688a51b + IQKeyboardCore: 8652977ec919cf5351aa2977fedd1a6546476fbc + IQKeyboardManagerSwift: 835fc9c6e4732398113406d84900ad2e8f141218 + IQKeyboardNotification: eb4910401f5a0e68f97e71c62f8a0c5b7e9d535c + IQKeyboardReturnManager: fcbf51fc68d7536fc1fbcca5231c4e82576b12ac + IQKeyboardToolbar: 9fe900f8e7def414be4025af0ca098df764d4fe3 + IQKeyboardToolbarManager: d449479b5843d4a3fb902d03bf62d6ca031ac20e + IQTextInputViewNotification: 3b9fb27a16e7ee8958cc9092cfb07a1a9e1fd559 + IQTextView: ae13b4922f22e6f027f62c557d9f4f236b19d5c7 + Kingfisher: fc2788e497306f97fdef6e4df49f02106cb57788 + KingfisherWebP: 064869d5f1201396ec121dcc4c9cfbdba6ecb900 + libwebp: 02b23773aedb6ff1fd38cec7a77b81414c6842a8 + MarqueeLabel: 0c57d4c6634e04a6d015af79f7c9a175b2309525 + Masonry: 678fab65091a9290e40e2832a55e7ab731aad201 + MBProgressHUD: 1b0fb447e80a0fda94808180750e8b78a07b3cd2 + MJRefresh: ff9e531227924c84ce459338414550a05d2aea78 + Moya: 138f0573e53411fb3dc17016add0b748dfbd78ee + ObjectMapper: e6e4d91ff7f2861df7aecc536c92d8363f4c9677 + Popover: 10e1d9528f81d9504df984b7b3f491292bc1822d + RxCocoa: 2d33c1e1e5d66492052ad46b11024ae287572880 + RxDataSources: aa47cc1ed6c500fa0dfecac5c979b723542d79cf + RxRelay: 335c78b926a2aea8d863a6d25f1ed3b5ad8e8705 + RxSwift: 4e28be97cbcfeee614af26d83415febbf2bf6f45 + RxSwiftExt: 43aaacb6a4d3c69c55e9d1cf4f79920043d13583 + SGQRCode: 6ad664d63f38f2842503bc5087812c5a3136d924 + SnapKit: d612e99e678a2d3b95bf60b0705ed0a35c03484a + SwiftDate: bbc26e26fc8c0c33fbee8c140c5e8a68293a148a + SwiftKeychainWrapper: 807ba1d63c33a7d0613288512399cd1eda1e470c + SwiftyJSON: f5b1bf1cd8dd53cd25887ac0eabcfd92301c6a5a + SwiftyUserDefaults: 63f80248cf5bfb3458825d9a78f2eb7e1293a040 + URLNavigator: e9c0426ba6e6ac57f34d018bbf3df840797f984d + ZXSDK: 786338c0a18e98e03eda00699c3bfd2700b97117 + +PODFILE CHECKSUM: 8221656bba011c856037590658f6282ed7f4e02c + +COCOAPODS: 1.16.2 diff --git a/QuickLocation.xcodeproj/project.pbxproj b/QuickLocation.xcodeproj/project.pbxproj new file mode 100644 index 00000000..7f434e81 --- /dev/null +++ b/QuickLocation.xcodeproj/project.pbxproj @@ -0,0 +1,463 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + C03BCA796B982B5ACA9611EE /* Pods_QuickLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E143BF7B4D1F77827EB9982E /* Pods_QuickLocation.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 3E4359082FC48D26003470A5 /* QuickLocation.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QuickLocation.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C2BE08A1B1E96CAB0EE3C077 /* Pods-QuickLocation.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-QuickLocation.release.xcconfig"; path = "Target Support Files/Pods-QuickLocation/Pods-QuickLocation.release.xcconfig"; sourceTree = ""; }; + DD686BFD90D3CEEEFABFE88F /* Pods-QuickLocation.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-QuickLocation.debug.xcconfig"; path = "Target Support Files/Pods-QuickLocation/Pods-QuickLocation.debug.xcconfig"; sourceTree = ""; }; + E143BF7B4D1F77827EB9982E /* Pods_QuickLocation.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_QuickLocation.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + 3E43591A2FC48D2B003470A5 /* Exceptions for "QuickLocation" folder in "QuickLocation" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 3E4359072FC48D26003470A5 /* QuickLocation */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 3E43590A2FC48D26003470A5 /* QuickLocation */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 3E43591A2FC48D2B003470A5 /* Exceptions for "QuickLocation" folder in "QuickLocation" target */, + ); + path = QuickLocation; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 3E4359052FC48D26003470A5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C03BCA796B982B5ACA9611EE /* Pods_QuickLocation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1CFEE11C08437C3618FD06EF /* Frameworks */ = { + isa = PBXGroup; + children = ( + E143BF7B4D1F77827EB9982E /* Pods_QuickLocation.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 3E4358FF2FC48D26003470A5 = { + isa = PBXGroup; + children = ( + 3E43590A2FC48D26003470A5 /* QuickLocation */, + 3E4359092FC48D26003470A5 /* Products */, + B07D45692FCECE07570D9B73 /* Pods */, + 1CFEE11C08437C3618FD06EF /* Frameworks */, + ); + sourceTree = ""; + }; + 3E4359092FC48D26003470A5 /* Products */ = { + isa = PBXGroup; + children = ( + 3E4359082FC48D26003470A5 /* QuickLocation.app */, + ); + name = Products; + sourceTree = ""; + }; + B07D45692FCECE07570D9B73 /* Pods */ = { + isa = PBXGroup; + children = ( + DD686BFD90D3CEEEFABFE88F /* Pods-QuickLocation.debug.xcconfig */, + C2BE08A1B1E96CAB0EE3C077 /* Pods-QuickLocation.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 3E4359072FC48D26003470A5 /* QuickLocation */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3E43591B2FC48D2B003470A5 /* Build configuration list for PBXNativeTarget "QuickLocation" */; + buildPhases = ( + 6351E02EF2A14F505ED2090F /* [CP] Check Pods Manifest.lock */, + 3E4359042FC48D26003470A5 /* Sources */, + 3E4359052FC48D26003470A5 /* Frameworks */, + 3E4359062FC48D26003470A5 /* Resources */, + 6DA31A37CE44CF6C53CFCC77 /* [CP] Embed Pods Frameworks */, + F1F67E9D9FD03DDF6DB237AC /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 3E43590A2FC48D26003470A5 /* QuickLocation */, + ); + name = QuickLocation; + productName = QuickLocation; + productReference = 3E4359082FC48D26003470A5 /* QuickLocation.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 3E4359002FC48D26003470A5 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2600; + LastUpgradeCheck = 2600; + TargetAttributes = { + 3E4359072FC48D26003470A5 = { + CreatedOnToolsVersion = 26.0.1; + }; + }; + }; + buildConfigurationList = 3E4359032FC48D26003470A5 /* Build configuration list for PBXProject "QuickLocation" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 3E4358FF2FC48D26003470A5; + minimizedProjectReferenceProxies = 1; + preferredProjectObjectVersion = 77; + productRefGroup = 3E4359092FC48D26003470A5 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 3E4359072FC48D26003470A5 /* QuickLocation */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 3E4359062FC48D26003470A5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 6351E02EF2A14F505ED2090F /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-QuickLocation-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 6DA31A37CE44CF6C53CFCC77 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + F1F67E9D9FD03DDF6DB237AC /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-resources-${CONFIGURATION}-input-files.xcfilelist", + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-resources-${CONFIGURATION}-output-files.xcfilelist", + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 3E4359042FC48D26003470A5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 3E43591C2FC48D2B003470A5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DD686BFD90D3CEEEFABFE88F /* Pods-QuickLocation.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7LP48T8ZJE; + ENABLE_USER_SCRIPT_SANDBOXING = "$(inherited)"; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = QuickLocation/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = "极速定位"; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + IPHONEOS_DEPLOYMENT_TARGET = 15; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = cn.zuom8.jisuloca; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OBJC_BRIDGING_HEADER = "QuickLocation/QuickLocation-Bridging-Header.h"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 3E43591D2FC48D2B003470A5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C2BE08A1B1E96CAB0EE3C077 /* Pods-QuickLocation.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7LP48T8ZJE; + ENABLE_USER_SCRIPT_SANDBOXING = "$(inherited)"; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = QuickLocation/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = "极速定位"; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + IPHONEOS_DEPLOYMENT_TARGET = 15; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = cn.zuom8.jisuloca; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OBJC_BRIDGING_HEADER = "QuickLocation/QuickLocation-Bridging-Header.h"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 3E43591E2FC48D2B003470A5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = "$(inherited)"; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 3E43591F2FC48D2B003470A5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = "$(inherited)"; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 3E4359032FC48D26003470A5 /* Build configuration list for PBXProject "QuickLocation" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3E43591E2FC48D2B003470A5 /* Debug */, + 3E43591F2FC48D2B003470A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3E43591B2FC48D2B003470A5 /* Build configuration list for PBXNativeTarget "QuickLocation" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3E43591C2FC48D2B003470A5 /* Debug */, + 3E43591D2FC48D2B003470A5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 3E4359002FC48D26003470A5 /* Project object */; +} diff --git a/QuickLocation.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/QuickLocation.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/QuickLocation.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/QuickLocation.xcodeproj/project.xcworkspace/xcuserdata/lin.xcuserdatad/UserInterfaceState.xcuserstate b/QuickLocation.xcodeproj/project.xcworkspace/xcuserdata/lin.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 00000000..67260dc4 Binary files /dev/null and b/QuickLocation.xcodeproj/project.xcworkspace/xcuserdata/lin.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/QuickLocation.xcodeproj/xcshareddata/xcschemes/QuickLocation.xcscheme b/QuickLocation.xcodeproj/xcshareddata/xcschemes/QuickLocation.xcscheme new file mode 100644 index 00000000..2bfe6a68 --- /dev/null +++ b/QuickLocation.xcodeproj/xcshareddata/xcschemes/QuickLocation.xcscheme @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickLocation.xcodeproj/xcuserdata/lin.xcuserdatad/xcschemes/xcschememanagement.plist b/QuickLocation.xcodeproj/xcuserdata/lin.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000..4df0e857 --- /dev/null +++ b/QuickLocation.xcodeproj/xcuserdata/lin.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + QuickLocation.xcscheme_^#shared#^_ + + orderHint + 39 + + + + diff --git a/QuickLocation.xcodeproj/xcuserdata/yanghong.xcuserdatad/xcschemes/xcschememanagement.plist b/QuickLocation.xcodeproj/xcuserdata/yanghong.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000..0af32016 --- /dev/null +++ b/QuickLocation.xcodeproj/xcuserdata/yanghong.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,22 @@ + + + + + SchemeUserState + + QuickLocation.xcscheme_^#shared#^_ + + orderHint + 42 + + + SuppressBuildableAutocreation + + 3E4359072FC48D26003470A5 + + primary + + + + + diff --git a/QuickLocation.xcworkspace/contents.xcworkspacedata b/QuickLocation.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..bce797b0 --- /dev/null +++ b/QuickLocation.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/QuickLocation.xcworkspace/xcuserdata/lin.xcuserdatad/UserInterfaceState.xcuserstate b/QuickLocation.xcworkspace/xcuserdata/lin.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 00000000..dd985ca0 Binary files /dev/null and b/QuickLocation.xcworkspace/xcuserdata/lin.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/QuickLocation.xcworkspace/xcuserdata/yanghong.xcuserdatad/UserInterfaceState.xcuserstate b/QuickLocation.xcworkspace/xcuserdata/yanghong.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 00000000..293485d6 Binary files /dev/null and b/QuickLocation.xcworkspace/xcuserdata/yanghong.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/QuickLocation.xcworkspace/xcuserdata/yanghong.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/QuickLocation.xcworkspace/xcuserdata/yanghong.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 00000000..a5519e7c --- /dev/null +++ b/QuickLocation.xcworkspace/xcuserdata/yanghong.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,6 @@ + + + diff --git a/QuickLocation/API/API.swift b/QuickLocation/API/API.swift new file mode 100644 index 00000000..bbc7c4ac --- /dev/null +++ b/QuickLocation/API/API.swift @@ -0,0 +1,33 @@ +// +// API.swift +// HealthyZG +// +// Created by 林 on 2020/5/15. +// Copyright © 2020 Lin. All rights reserved. +// + +import Moya +import SwiftyUserDefaults + +public protocol MultiTargetProtocol: TargetType { + var multiTarget: MultiTarget { get } +} + +public extension MultiTargetProtocol { + + var multiTarget: MultiTarget { MultiTarget(self) } + + var headers: [String : String]? { + AppNetworkConfig.shared.httpHeader?() + } + + var baseURL: URL { URL(string: AppNetworkConfig.shared.baseURL)! } + + var parameters: [String : Any] { + var parameters: [String : Any] = [:] + + return parameters + } + + var sampleData: Data { Data(base64Encoded: "just for test")! } +} diff --git a/QuickLocation/API/APIProvider.swift b/QuickLocation/API/APIProvider.swift new file mode 100644 index 00000000..d7c38f10 --- /dev/null +++ b/QuickLocation/API/APIProvider.swift @@ -0,0 +1,131 @@ +// +// APIProvider.swift +// HealthyZG +// +// Created by 林 on 2020/5/18. +// Copyright © 2020 Lin. All rights reserved. +// + +import Foundation +import Moya +import RxSwift + +// swiftlint:disable:next identifier_name +public let GatewayStatusCodeKey = "GatewayStatusCodeKey" + +typealias Parameters = [String: Any] + +private func JSONResponseDataFormatter(_ data: Data) -> String { + do { + let dataAsJSON = try JSONSerialization.jsonObject(with: data) + let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) + return String(data: prettyData, encoding: .utf8) ?? String(data: data, encoding: .utf8) ?? "" + } catch { + return String(data: data, encoding: .utf8) ?? "" + } +} + +private func reversedPrint(_ separator: String, terminator: String, items: Any...) { + for item in items { + if let msg = item as? String { + LogInfo(msg) + } + } +} + +// MARK: - Provider setup +let requestClosure = { (endpoint: Endpoint, done: MoyaProvider.RequestResultClosure) in + do { + var request = try endpoint.urlRequest() + // Modify the request however you like. + request.timeoutInterval = 15 //设置请求超时时间 + done(.success(request)) + } catch { + done(.failure(MoyaError.underlying(error, nil))) + } +} + +let plugins: [PluginType] = [ + SignPlugin(), + NetworkLoggerPlugin(configuration: .init(formatter: .init(responseData: JSONResponseDataFormatter), logOptions: .verbose)), + NetworkActivityPlugin(networkActivityClosure: { change, _ in + #if !SHARE_EXTENSION + DispatchQueue.main.async { + switch change { + case .began: + UIApplication.shared.isNetworkActivityIndicatorVisible = true + case .ended: + UIApplication.shared.isNetworkActivityIndicatorVisible = false + } + } + #endif + }) +] + +public let APIProvider = MoyaProvider(requestClosure: requestClosure, + plugins: plugins).rx +public extension Error { + var underlyingError: NSError? { + guard let moyaError = self as? MoyaError else { return nil } + guard case let .underlying(error, _) = moyaError else { return nil } + return error as NSError + } + + var gatewayStatusCode: Int { + let error = underlyingError ?? self as NSError + return error.code + } + + var gatewayMessage: String? { + let error = underlyingError ?? self as NSError + return error.userInfo[NSLocalizedDescriptionKey] as? String + } + + var responseData: Response? { + guard let moyaError = self as? MoyaError else { return nil } + guard case let .underlying(_, response) = moyaError else { return nil } + return response + } + + var isShowErrorTips: Bool { + let error = underlyingError ?? self as NSError + return error.userInfo["isShowTip"] as? Bool ?? true + } +} + +public extension MoyaError { + var innerError: NSError? { + switch self { + case let .encodableMapping(error): + return error as NSError + case let .objectMapping(error, _): + return error as NSError + case let .underlying(error, _): + return error as NSError + case let .parameterEncoding(error): + return error as NSError + default: + return nil + } + } +} + +// 网关状态码 +enum GatewayStatusCode: Int { + // 请求成功 + case success = 0 + // 版本过低 + case outdateVersion = 3 + /** ============== 风控 ============== */ + case riskControl = 701 + /** ============== 用户权限相关 200~300 ============== */ + // 登录失效 + case userLoginExpair = 1001003 + // 权限不足 + case noAuthority = 500 + // 审核中 + case review = 201 + + /** ============== 未知错误 ============== */ + case unknownError = -9999 +} diff --git a/QuickLocation/API/AppNetworkConfig.swift b/QuickLocation/API/AppNetworkConfig.swift new file mode 100644 index 00000000..e74d4405 --- /dev/null +++ b/QuickLocation/API/AppNetworkConfig.swift @@ -0,0 +1,33 @@ +// +// AppNetworkConfig.swift +// SHECommunity +// +// Created by 林 on 2024/11/25. +// + +import Foundation +import Moya + +// 网络配置 +class AppNetworkConfig { + // MARK: - Property + /// 单例 + public static let shared = AppNetworkConfig() + + /// 服务器地址 + public var baseURL: String = "" + + /// 请求header + public var httpHeader: (() -> [String: String])? + + /// 处理接口请求数据 + public var handleRespone: ((Result, Bool) -> Result?)? + + // MARK: - Lifecyc + private init() {} + +} + +extension AppNetworkConfig { + +} diff --git a/QuickLocation/API/RxMoya/MoyaProvider+Rx.swift b/QuickLocation/API/RxMoya/MoyaProvider+Rx.swift new file mode 100644 index 00000000..3d05560c --- /dev/null +++ b/QuickLocation/API/RxMoya/MoyaProvider+Rx.swift @@ -0,0 +1,65 @@ +import Foundation +import RxSwift +import Moya +import SwiftyJSON + +extension MoyaProvider: @retroactive ReactiveCompatible {} + +public extension Reactive where Base: MoyaProviderType { + + /// Designated request-making method. + /// + /// - Parameters: + /// - token: Entity, which provides specifications necessary for a `MoyaProvider`. + /// - callbackQueue: Callback queue. If nil - queue from provider initializer will be used. + /// - Returns: Single response object. + func request(token: Base.Target, handle: Bool = true, callbackQueue: DispatchQueue? = nil) -> Single { + return Single.create { [weak base] single in + let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in + if let newResult = AppNetworkConfig.shared.handleRespone?(result, handle) { + switch newResult { + case let .success(response): + single(.success(response)) + case let .failure(error): + single(.failure(error)) + } + } + } + + return Disposables.create { + cancellableToken?.cancel() + } + } + } + + /// Designated request-making method with progress. + func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable { + let progressBlock: (AnyObserver) -> (ProgressResponse) -> Void = { observer in + return { progress in + observer.onNext(progress) + } + } + + let response: Observable = Observable.create { [weak base] observer in + let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: progressBlock(observer)) { result in + switch result { + case .success: + observer.onCompleted() + case let .failure(error): + observer.onError(error) + } + } + + return Disposables.create { + cancellableToken?.cancel() + } + } + + // Accumulate all progress and combine them when the result comes + return response.scan(ProgressResponse()) { last, progress in + let progressObject = progress.progressObject ?? last.progressObject + let response = progress.response ?? last.response + return ProgressResponse(progress: progressObject, response: response) + } + } +} diff --git a/QuickLocation/API/RxMoya/Observable+Response.swift b/QuickLocation/API/RxMoya/Observable+Response.swift new file mode 100644 index 00000000..fa1036dc --- /dev/null +++ b/QuickLocation/API/RxMoya/Observable+Response.swift @@ -0,0 +1,82 @@ +import Foundation +import RxSwift +import Moya + +#if canImport(UIKit) + import UIKit.UIImage +#elseif canImport(AppKit) + import AppKit.NSImage +#endif + +/// Extension for processing raw NSData generated by network access. +public extension ObservableType where Element == Response { + + /// Filters out responses that don't fall within the given range, generating errors when others are encountered. + func filter(statusCodes: R) -> Observable where R.Bound == Int { + return flatMap { Observable.just(try $0.filter(statusCodes: statusCodes)) } + } + + /// Filters out responses that has the specified `statusCode`. + func filter(statusCode: Int) -> Observable { + return flatMap { Observable.just(try $0.filter(statusCode: statusCode)) } + } + + /// Filters out responses where `statusCode` falls within the range 200 - 299. + func filterSuccessfulStatusCodes() -> Observable { + return flatMap { Observable.just(try $0.filterSuccessfulStatusCodes()) } + } + + /// Filters out responses where `statusCode` falls within the range 200 - 399 + func filterSuccessfulStatusAndRedirectCodes() -> Observable { + return flatMap { Observable.just(try $0.filterSuccessfulStatusAndRedirectCodes()) } + } + + /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. + func mapImage() -> Observable { + return flatMap { Observable.just(try $0.mapImage()) } + } + + /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors. + func mapJSON(failsOnEmptyData: Bool = true) -> Observable { + return flatMap { Observable.just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) } + } + + /// Maps received data at key path into a String. If the conversion fails, the signal errors. + func mapString(atKeyPath keyPath: String? = nil) -> Observable { + return flatMap { Observable.just(try $0.mapString(atKeyPath: keyPath)) } + } + + /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors. + func map(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> Observable { + return flatMap { Observable.just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) } + } +} + +public extension ObservableType where Element == ProgressResponse { + + /** + Filter completed progress response and maps to actual response + + - returns: response associated with ProgressResponse object + */ + func filterCompleted() -> Observable { + return self + .filter { $0.completed } + .flatMap { progress -> Observable in + // Just a formatlity to satisfy the compiler (completed progresses have responses). + switch progress.response { + case .some(let response): return .just(response) + case .none: return .empty() + } + } + } + + /** + Filter progress events of current ProgressResponse + + - returns: observable of progress events + */ + func filterProgress() -> Observable { + return self.filter { !$0.completed }.map { $0.progress } + } +} diff --git a/QuickLocation/API/RxMoya/Single+Response.swift b/QuickLocation/API/RxMoya/Single+Response.swift new file mode 100644 index 00000000..236147a9 --- /dev/null +++ b/QuickLocation/API/RxMoya/Single+Response.swift @@ -0,0 +1,53 @@ +import Foundation +import RxSwift +import Moya + +#if canImport(UIKit) + import UIKit.UIImage +#elseif canImport(AppKit) + import AppKit.NSImage +#endif + +/// Extension for processing raw NSData generated by network access. +public extension PrimitiveSequence where Trait == SingleTrait, Element == Response { + + /// Filters out responses that don't fall within the given closed range, generating errors when others are encountered. + func filter(statusCodes: R) -> Single where R.Bound == Int { + return flatMap { .just(try $0.filter(statusCodes: statusCodes)) } + } + + /// Filters out responses that have the specified `statusCode`. + func filter(statusCode: Int) -> Single { + return flatMap { .just(try $0.filter(statusCode: statusCode)) } + } + + /// Filters out responses where `statusCode` falls within the range 200 - 299. + func filterSuccessfulStatusCodes() -> Single { + return flatMap { .just(try $0.filterSuccessfulStatusCodes()) } + } + + /// Filters out responses where `statusCode` falls within the range 200 - 399 + func filterSuccessfulStatusAndRedirectCodes() -> Single { + return flatMap { .just(try $0.filterSuccessfulStatusAndRedirectCodes()) } + } + + /// Maps data received from the signal into an Image. If the conversion fails, the signal errors. + func mapImage() -> Single { + return flatMap { .just(try $0.mapImage()) } + } + + /// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors. + func mapJSON(failsOnEmptyData: Bool = true) -> Single { + return flatMap { .just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) } + } + + /// Maps received data at key path into a String. If the conversion fails, the signal errors. + func mapString(atKeyPath keyPath: String? = nil) -> Single { + return flatMap { .just(try $0.mapString(atKeyPath: keyPath)) } + } + + /// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors. + func map(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> Single { + return flatMap { .just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) } + } +} diff --git a/QuickLocation/API/SignPlugin.swift b/QuickLocation/API/SignPlugin.swift new file mode 100644 index 00000000..9425f6c2 --- /dev/null +++ b/QuickLocation/API/SignPlugin.swift @@ -0,0 +1,82 @@ +import Foundation +import Moya +import CommonCrypto + +/// JiaMiKey 的 MD5,预计算避免每次请求都算 +private let jiaMiKeyMD5: String = { + let key = "857d69d374694c1de46486d3bdaaac43" + return SignPlugin.md5(key) +}() + +/// 请求签名 Plugin +final class SignPlugin: PluginType { + + func prepare(_ request: URLRequest, target: any TargetType) -> URLRequest { + var mutableRequest = request + + guard let url = request.url else { return mutableRequest } + + let timestamp = String(format: "%.0lf", Date().timeIntervalSince1970) + let nonce = randomString(length: 32) + + var queryDict: [String: String] = [ + "timestamp": timestamp, + "nonce": nonce + ] + + // 收集 URL 已有的 query 参数,一并纳入签名 + if let components = URLComponents(url: url, resolvingAgainstBaseURL: false), + let queryItems = components.queryItems { + for item in queryItems { + queryDict[item.name] = item.value ?? "" + } + } + + let bodyString: String + if let httpBody = request.httpBody, !httpBody.isEmpty { + bodyString = String(data: httpBody, encoding: .utf8) ?? "" + } else { + bodyString = "" + } + + let queryString = sortedQueryString(queryDict) + let signStr: String + if bodyString.isEmpty { + signStr = queryString + "&" + jiaMiKeyMD5 + } else { + signStr = queryString + "&" + bodyString + "&" + jiaMiKeyMD5 + } + let signature = Self.md5(signStr) + + // 剥离旧 query,替换为完整的签名 query + let signedQuery = queryString + "&signature=" + signature + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + components?.percentEncodedQuery = signedQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) + + if let newURL = components?.url { + mutableRequest.url = newURL + } + + return mutableRequest + } + + private func sortedQueryString(_ dict: [String: String]) -> String { + dict + .sorted { $0.key < $1.key } + .map { "\($0.key)=\($0.value)" } + .joined(separator: "&") + } + + private func randomString(length: Int) -> String { + let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + return String((0.. String { + let cStr = string.cString(using: .utf8) + let length = CC_LONG(strlen(cStr!)) + var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) + CC_MD5(cStr, length, &digest) + return digest.map { String(format: "%02x", $0) }.joined() + } +} diff --git a/QuickLocation/API/SystemAPI.swift b/QuickLocation/API/SystemAPI.swift new file mode 100644 index 00000000..462b7f37 --- /dev/null +++ b/QuickLocation/API/SystemAPI.swift @@ -0,0 +1,55 @@ +// +// SystemAPI.swift +// SHECommunity +// +// Created by 林 on 2024/11/27. +// + +import Moya +internal import Alamofire + +/// App通用API +enum SystemAPI { + /// 获取用户配置 + case userConfig + + /// 发送验证码 + /// - Parameters: + /// - phone: 手机号 + case sendCode(phone: String) + + +} + +extension SystemAPI: MultiTargetProtocol { + + var path: String { + switch self { + case .userConfig: + return "api/user/config" + case .sendCode: + return "api/user/sms/code" + } + } + + var method: Moya.Method { + switch self { + case .userConfig: + return .get + case .sendCode: + return .post + } + } + + var task: Moya.Task { + switch self { + case .userConfig: + return .requestParameters(parameters: parameters, encoding: URLEncoding()) + + case let .sendCode(phone): + var params = Parameters() + params["phone"] = phone + return .requestParameters(parameters: params, encoding: JSONEncoding()) + } + } +} diff --git a/QuickLocation/API/UserAPI.swift b/QuickLocation/API/UserAPI.swift new file mode 100644 index 00000000..788350a7 --- /dev/null +++ b/QuickLocation/API/UserAPI.swift @@ -0,0 +1,60 @@ +// +// UserAPI.swift +// QuickLocation +// +// Created by 八条 on 2026/5/28. +// + +import Moya +import SwiftyUserDefaults +internal import Alamofire + +/// 用户相关API +enum UserAPI { + /// 登录 + /// - Parameters: + /// - type: weixin、phone、apple、onekey、device、alipay + /// - bind:1绑定 2解绑 为空是登录 + case login(type: String, + bind: String, + data: [String: Any]) + + /// 退出登录 + case logout +} + +extension UserAPI: MultiTargetProtocol { + + var path: String { + switch self { + case .login: + return "api/user/login" + case .logout: + return "api/user/logout" + } + } + + var method: Moya.Method { + .post +// switch self { +// case .: +// return .get +// case .login: +// return .post +// } + } + + var task: Moya.Task { + switch self { + case let .login(type, bind, data): + var params = Parameters() + params["type"] = type + params["bind"] = bind + params["data"] = data + return .requestParameters(parameters: params, encoding: JSONEncoding()) + + case .logout: + return .requestParameters(parameters: Parameters(), encoding: JSONEncoding()) + } + } +} diff --git a/QuickLocation/AppDelegate.swift b/QuickLocation/AppDelegate.swift new file mode 100644 index 00000000..ccb0f311 --- /dev/null +++ b/QuickLocation/AppDelegate.swift @@ -0,0 +1,102 @@ +// +// AppDelegate.swift +// QuickLocation +// +// Created by 林 on 2026/5/25. +// + +import UIKit +import IQKeyboardManagerSwift +#if !targetEnvironment(simulator) +import GeYanSdk +import AMapFoundationKit +#endif + +@main +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { + + ApiManager.shared.setup() + AppRouter.shared.setup() + + return true + } + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + + IQKeyboardManager.shared.isEnabled = true + IQKeyboardManager.shared.enableAutoToolbar = false + IQKeyboardManager.shared.resignOnTouchOutside = true + + // 高德地图 + #if !targetEnvironment(simulator) + AMapServices.shared().apiKey = AppSettings.kAppsAMapAppId + #endif + + // 个推 + #if !targetEnvironment(simulator) + GeYanSdk.setPreLoginTimeout(10) + GeYanSdk.setEloginTimeout(10) + GeYanSdk.start(withAppId: AppSettings.kAppsGeTuiAppId) { isSuccess, error, gtcid in + print("GeYanSdk startWithAppId gtcid: \(gtcid ?? "")") + } + GeYanSdk.preGetToken { preDic in + print("preGetToken: \(preDic)") + } + #endif + + + window = UIWindow(frame: UIScreen.main.bounds) + window?.backgroundColor = .white + window?.overrideUserInterfaceStyle = .light + window?.rootViewController = LaunchViewController() + window?.makeKeyAndVisible() + + return true + } +} + +extension AppDelegate { + /// 重置MainTabbarViewController + func showMainViewController() { + window?.rootViewController = MainTabBarController() + } +} + +extension AppDelegate { + + static var shared: AppDelegate { + UIApplication.shared.delegate as! AppDelegate + } + + static var keyWindow: UIWindow? { + UIApplication.shared.windows.filter { $0.isKeyWindow }.first + } + + static var rootViewController: UIViewController? { + getRootViewController(keyWindow?.rootViewController) + } + + static func getRootViewController(_ inViewController: UIViewController?) -> UIViewController? { + + var rootViewController: UIViewController? = inViewController + + while inViewController?.presentedViewController != nil { + rootViewController = rootViewController?.presentedViewController + } + + guard let rootVc = rootViewController else { return nil } + + if rootVc.isKind(of: UINavigationController.self) { + return getRootViewController((rootVc as? UINavigationController)?.visibleViewController) + } else if rootVc.isKind(of: UITabBarController.self) { + return getRootViewController((rootVc as? UITabBarController)?.selectedViewController) + } else { + return rootVc + } + } +} diff --git a/QuickLocation/Assets.xcassets/AccentColor.colorset/Contents.json b/QuickLocation/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 00000000..eb878970 --- /dev/null +++ b/QuickLocation/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/AppIcon.appiconset/Contents.json b/QuickLocation/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..ddd0a373 --- /dev/null +++ b/QuickLocation/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,36 @@ +{ + "images" : [ + { + "filename" : "app_icon.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "tinted" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/AppIcon.appiconset/app_icon.png b/QuickLocation/Assets.xcassets/AppIcon.appiconset/app_icon.png new file mode 100644 index 00000000..8a299af2 Binary files /dev/null and b/QuickLocation/Assets.xcassets/AppIcon.appiconset/app_icon.png differ diff --git a/QuickLocation/Assets.xcassets/Common/Contents.json b/QuickLocation/Assets.xcassets/Common/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Common/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Common/back.imageset/Contents.json b/QuickLocation/Assets.xcassets/Common/back.imageset/Contents.json new file mode 100644 index 00000000..79099b29 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Common/back.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "back@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "back@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Common/back.imageset/back@2x.png b/QuickLocation/Assets.xcassets/Common/back.imageset/back@2x.png new file mode 100644 index 00000000..ce73b942 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Common/back.imageset/back@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Common/back.imageset/back@3x.png b/QuickLocation/Assets.xcassets/Common/back.imageset/back@3x.png new file mode 100644 index 00000000..f938c49c Binary files /dev/null and b/QuickLocation/Assets.xcassets/Common/back.imageset/back@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/Contents.json b/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/Contents.json new file mode 100644 index 00000000..4fd1c39f --- /dev/null +++ b/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "navBar_bg_1@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "navBar_bg_1@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/navBar_bg_1@2x.png b/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/navBar_bg_1@2x.png new file mode 100644 index 00000000..5b8659af Binary files /dev/null and b/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/navBar_bg_1@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/navBar_bg_1@3x.png b/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/navBar_bg_1@3x.png new file mode 100644 index 00000000..84a66f62 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Common/navBar_bg_1.imageset/navBar_bg_1@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/Contents.json b/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/Contents.json new file mode 100644 index 00000000..9976501d --- /dev/null +++ b/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "navBar_bg_2@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "navBar_bg_2@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/navBar_bg_2@2x.png b/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/navBar_bg_2@2x.png new file mode 100644 index 00000000..2a5d2717 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/navBar_bg_2@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/navBar_bg_2@3x.png b/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/navBar_bg_2@3x.png new file mode 100644 index 00000000..0be4d09c Binary files /dev/null and b/QuickLocation/Assets.xcassets/Common/navBar_bg_2.imageset/navBar_bg_2@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Contents.json b/QuickLocation/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/Contents.json b/QuickLocation/Assets.xcassets/Guide/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/experience.imageset/Contents.json b/QuickLocation/Assets.xcassets/Guide/experience.imageset/Contents.json new file mode 100644 index 00000000..c7d1dd31 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/experience.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Rectangle 71@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Rectangle 71@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/experience.imageset/Rectangle 71@2x.png b/QuickLocation/Assets.xcassets/Guide/experience.imageset/Rectangle 71@2x.png new file mode 100644 index 00000000..2e8a769f Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/experience.imageset/Rectangle 71@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/experience.imageset/Rectangle 71@3x.png b/QuickLocation/Assets.xcassets/Guide/experience.imageset/Rectangle 71@3x.png new file mode 100644 index 00000000..449dac18 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/experience.imageset/Rectangle 71@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Contents.json b/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Contents.json new file mode 100644 index 00000000..74408af2 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_2040@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_2040@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Group_2040@2x.png b/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Group_2040@2x.png new file mode 100644 index 00000000..c527ecb0 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Group_2040@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Group_2040@3x.png b/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Group_2040@3x.png new file mode 100644 index 00000000..997a55cf Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_1.imageset/Group_2040@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Contents.json b/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Contents.json new file mode 100644 index 00000000..bb8a43d6 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_2041@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_2041@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Group_2041@2x.png b/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Group_2041@2x.png new file mode 100644 index 00000000..04512c44 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Group_2041@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Group_2041@3x.png b/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Group_2041@3x.png new file mode 100644 index 00000000..3cc133e0 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_2.imageset/Group_2041@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Contents.json b/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Contents.json new file mode 100644 index 00000000..7fba5ace --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_2042@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_2042@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Group_2042@2x.png b/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Group_2042@2x.png new file mode 100644 index 00000000..f32a0c46 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Group_2042@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Group_2042@3x.png b/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Group_2042@3x.png new file mode 100644 index 00000000..ba3f91cd Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_3.imageset/Group_2042@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Contents.json b/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Contents.json new file mode 100644 index 00000000..3a3637c7 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_2043@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_2043@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Group_2043@2x.png b/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Group_2043@2x.png new file mode 100644 index 00000000..a34e12ec Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Group_2043@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Group_2043@3x.png b/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Group_2043@3x.png new file mode 100644 index 00000000..497d5f67 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_4.imageset/Group_2043@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Contents.json b/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Contents.json new file mode 100644 index 00000000..14e39f8b --- /dev/null +++ b/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_2044@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_2044@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Group_2044@2x.png b/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Group_2044@2x.png new file mode 100644 index 00000000..8d2f2faa Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Group_2044@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Group_2044@3x.png b/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Group_2044@3x.png new file mode 100644 index 00000000..5a3b6da8 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Guide/guide_5.imageset/Group_2044@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/Contents.json b/QuickLocation/Assets.xcassets/Home/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/Contents.json new file mode 100644 index 00000000..590524c1 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "􀆉_Parent View@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "􀆉_Parent View@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/􀆉_Parent View@2x.png b/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/􀆉_Parent View@2x.png new file mode 100644 index 00000000..3e4c1e37 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/􀆉_Parent View@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/􀆉_Parent View@3x.png b/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/􀆉_Parent View@3x.png new file mode 100644 index 00000000..0e34b3ea Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/arrow_down.imageset/􀆉_Parent View@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/bubble.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/bubble.imageset/Contents.json new file mode 100644 index 00000000..0d15a706 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/bubble.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group 1917@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group 1917@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/bubble.imageset/Group 1917@2x.png b/QuickLocation/Assets.xcassets/Home/bubble.imageset/Group 1917@2x.png new file mode 100644 index 00000000..6e0a0cc2 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/bubble.imageset/Group 1917@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/bubble.imageset/Group 1917@3x.png b/QuickLocation/Assets.xcassets/Home/bubble.imageset/Group 1917@3x.png new file mode 100644 index 00000000..2e0e579e Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/bubble.imageset/Group 1917@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/direction.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/direction.imageset/Contents.json new file mode 100644 index 00000000..da781cbc --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/direction.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "direction@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "direction@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/direction.imageset/direction@2x.png b/QuickLocation/Assets.xcassets/Home/direction.imageset/direction@2x.png new file mode 100644 index 00000000..2dbd53b0 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/direction.imageset/direction@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/direction.imageset/direction@3x.png b/QuickLocation/Assets.xcassets/Home/direction.imageset/direction@3x.png new file mode 100644 index 00000000..8fdf5f5c Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/direction.imageset/direction@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/group.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/group.imageset/Contents.json new file mode 100644 index 00000000..8a443db5 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/group.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "group@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "group@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/group.imageset/group@2x.png b/QuickLocation/Assets.xcassets/Home/group.imageset/group@2x.png new file mode 100644 index 00000000..3eb5e6f4 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/group.imageset/group@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/group.imageset/group@3x.png b/QuickLocation/Assets.xcassets/Home/group.imageset/group@3x.png new file mode 100644 index 00000000..af783296 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/group.imageset/group@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/location.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/location.imageset/Contents.json new file mode 100644 index 00000000..e3bf7136 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/location.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_50@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_50@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/location.imageset/Group_50@2x.png b/QuickLocation/Assets.xcassets/Home/location.imageset/Group_50@2x.png new file mode 100644 index 00000000..771286b5 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/location.imageset/Group_50@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/location.imageset/Group_50@3x.png b/QuickLocation/Assets.xcassets/Home/location.imageset/Group_50@3x.png new file mode 100644 index 00000000..ab523a8e Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/location.imageset/Group_50@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/Contents.json new file mode 100644 index 00000000..7bd730dc --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "navBar_bg@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "navBar_bg@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/navBar_bg@2x.png b/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/navBar_bg@2x.png new file mode 100644 index 00000000..b62fe0df Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/navBar_bg@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/navBar_bg@3x.png b/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/navBar_bg@3x.png new file mode 100644 index 00000000..26d77b50 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/navBar_bg.imageset/navBar_bg@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/search.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/search.imageset/Contents.json new file mode 100644 index 00000000..057e77ae --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/search.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_1512@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_1512@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/search.imageset/Group_1512@2x.png b/QuickLocation/Assets.xcassets/Home/search.imageset/Group_1512@2x.png new file mode 100644 index 00000000..918b8651 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/search.imageset/Group_1512@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/search.imageset/Group_1512@3x.png b/QuickLocation/Assets.xcassets/Home/search.imageset/Group_1512@3x.png new file mode 100644 index 00000000..0857bd7f Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/search.imageset/Group_1512@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/signIn.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/signIn.imageset/Contents.json new file mode 100644 index 00000000..26e04946 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/signIn.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_1450@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_1450@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/signIn.imageset/Group_1450@2x.png b/QuickLocation/Assets.xcassets/Home/signIn.imageset/Group_1450@2x.png new file mode 100644 index 00000000..9c15a7a9 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/signIn.imageset/Group_1450@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/signIn.imageset/Group_1450@3x.png b/QuickLocation/Assets.xcassets/Home/signIn.imageset/Group_1450@3x.png new file mode 100644 index 00000000..c7c7c469 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/signIn.imageset/Group_1450@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/sos.imageset/Contents.json b/QuickLocation/Assets.xcassets/Home/sos.imageset/Contents.json new file mode 100644 index 00000000..80f9906d --- /dev/null +++ b/QuickLocation/Assets.xcassets/Home/sos.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_1449@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_1449@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Home/sos.imageset/Group_1449@2x.png b/QuickLocation/Assets.xcassets/Home/sos.imageset/Group_1449@2x.png new file mode 100644 index 00000000..ebdc1ab5 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/sos.imageset/Group_1449@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Home/sos.imageset/Group_1449@3x.png b/QuickLocation/Assets.xcassets/Home/sos.imageset/Group_1449@3x.png new file mode 100644 index 00000000..a0de5b43 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Home/sos.imageset/Group_1449@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Launch/Contents.json b/QuickLocation/Assets.xcassets/Launch/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Launch/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Launch/logo.imageset/Contents.json b/QuickLocation/Assets.xcassets/Launch/logo.imageset/Contents.json new file mode 100644 index 00000000..2b0beb8b --- /dev/null +++ b/QuickLocation/Assets.xcassets/Launch/logo.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_1483@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_1483@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Launch/logo.imageset/Group_1483@2x.png b/QuickLocation/Assets.xcassets/Launch/logo.imageset/Group_1483@2x.png new file mode 100644 index 00000000..68951d42 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Launch/logo.imageset/Group_1483@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Launch/logo.imageset/Group_1483@3x.png b/QuickLocation/Assets.xcassets/Launch/logo.imageset/Group_1483@3x.png new file mode 100644 index 00000000..eace6f07 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Launch/logo.imageset/Group_1483@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Contents.json b/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Contents.json new file mode 100644 index 00000000..c19b969f --- /dev/null +++ b/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_1482@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_1482@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Group_1482@2x.png b/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Group_1482@2x.png new file mode 100644 index 00000000..a87bed02 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Group_1482@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Group_1482@3x.png b/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Group_1482@3x.png new file mode 100644 index 00000000..6b4900a5 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Launch/slogan.imageset/Group_1482@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/Contents.json b/QuickLocation/Assets.xcassets/Login/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Login/apple.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/apple.imageset/Contents.json new file mode 100644 index 00000000..85c7d34f --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/apple.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group 1444@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group 1444@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/apple.imageset/Group 1444@2x.png b/QuickLocation/Assets.xcassets/Login/apple.imageset/Group 1444@2x.png new file mode 100644 index 00000000..cfb55532 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/apple.imageset/Group 1444@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/apple.imageset/Group 1444@3x.png b/QuickLocation/Assets.xcassets/Login/apple.imageset/Group 1444@3x.png new file mode 100644 index 00000000..58006457 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/apple.imageset/Group 1444@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/bg.imageset/Contents.json new file mode 100644 index 00000000..197fb605 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Mask_group@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Mask_group@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/bg.imageset/Mask_group@2x.png b/QuickLocation/Assets.xcassets/Login/bg.imageset/Mask_group@2x.png new file mode 100644 index 00000000..dc4fdf0e Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/bg.imageset/Mask_group@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/bg.imageset/Mask_group@3x.png b/QuickLocation/Assets.xcassets/Login/bg.imageset/Mask_group@3x.png new file mode 100644 index 00000000..ba975482 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/bg.imageset/Mask_group@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Contents.json new file mode 100644 index 00000000..a8dd92df --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Rectangle 209@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Rectangle 209@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Rectangle 209@2x.png b/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Rectangle 209@2x.png new file mode 100644 index 00000000..b20e4ca1 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Rectangle 209@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Rectangle 209@3x.png b/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Rectangle 209@3x.png new file mode 100644 index 00000000..f985f187 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/checkbox.imageset/Rectangle 209@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Contents.json new file mode 100644 index 00000000..d9f5b9f5 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Rectangle 72@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Rectangle 72@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Rectangle 72@2x.png b/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Rectangle 72@2x.png new file mode 100644 index 00000000..b1c863f1 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Rectangle 72@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Rectangle 72@3x.png b/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Rectangle 72@3x.png new file mode 100644 index 00000000..5c331849 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/login_bg.imageset/Rectangle 72@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/phone.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/phone.imageset/Contents.json new file mode 100644 index 00000000..0b7bbd3b --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/phone.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group 1445@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group 1445@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/phone.imageset/Group 1445@2x.png b/QuickLocation/Assets.xcassets/Login/phone.imageset/Group 1445@2x.png new file mode 100644 index 00000000..019b259b Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/phone.imageset/Group 1445@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/phone.imageset/Group 1445@3x.png b/QuickLocation/Assets.xcassets/Login/phone.imageset/Group 1445@3x.png new file mode 100644 index 00000000..737f8f84 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/phone.imageset/Group 1445@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/selected.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/selected.imageset/Contents.json new file mode 100644 index 00000000..5c56d9a8 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/selected.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group_1476@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group_1476@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/selected.imageset/Group_1476@2x.png b/QuickLocation/Assets.xcassets/Login/selected.imageset/Group_1476@2x.png new file mode 100644 index 00000000..193115cc Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/selected.imageset/Group_1476@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/selected.imageset/Group_1476@3x.png b/QuickLocation/Assets.xcassets/Login/selected.imageset/Group_1476@3x.png new file mode 100644 index 00000000..dcb90405 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/selected.imageset/Group_1476@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Contents.json new file mode 100644 index 00000000..95fec298 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Rectangle 71@2x 1.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Rectangle 71@3x 1.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Rectangle 71@2x 1.png b/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Rectangle 71@2x 1.png new file mode 100644 index 00000000..02f2656c Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Rectangle 71@2x 1.png differ diff --git a/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Rectangle 71@3x 1.png b/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Rectangle 71@3x 1.png new file mode 100644 index 00000000..c0897e93 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/visitor_bg.imageset/Rectangle 71@3x 1.png differ diff --git a/QuickLocation/Assets.xcassets/Login/wechat.imageset/Contents.json b/QuickLocation/Assets.xcassets/Login/wechat.imageset/Contents.json new file mode 100644 index 00000000..f979fa09 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Login/wechat.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Group 1446@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Group 1446@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Login/wechat.imageset/Group 1446@2x.png b/QuickLocation/Assets.xcassets/Login/wechat.imageset/Group 1446@2x.png new file mode 100644 index 00000000..aa5db5c8 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/wechat.imageset/Group 1446@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Login/wechat.imageset/Group 1446@3x.png b/QuickLocation/Assets.xcassets/Login/wechat.imageset/Group 1446@3x.png new file mode 100644 index 00000000..ead57b57 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Login/wechat.imageset/Group 1446@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/Contents.json b/QuickLocation/Assets.xcassets/Map/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/Contents.json new file mode 100644 index 00000000..f0eefaa2 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_bottom_controls@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_bottom_controls@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/map_bottom_controls@2x.png b/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/map_bottom_controls@2x.png new file mode 100644 index 00000000..af641423 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/map_bottom_controls@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/map_bottom_controls@3x.png b/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/map_bottom_controls@3x.png new file mode 100644 index 00000000..7b46ab10 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_bottom_controls.imageset/map_bottom_controls@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/Contents.json new file mode 100644 index 00000000..8c316698 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_bottom_panel_bg@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_bottom_panel_bg@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/map_bottom_panel_bg@2x.png b/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/map_bottom_panel_bg@2x.png new file mode 100644 index 00000000..79f3eb75 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/map_bottom_panel_bg@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/map_bottom_panel_bg@3x.png b/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/map_bottom_panel_bg@3x.png new file mode 100644 index 00000000..e1dc38de Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_bottom_panel_bg.imageset/map_bottom_panel_bg@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/Contents.json new file mode 100644 index 00000000..c26f40d2 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_btn_checkin@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_btn_checkin@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/map_btn_checkin@2x.png b/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/map_btn_checkin@2x.png new file mode 100644 index 00000000..06470f64 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/map_btn_checkin@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/map_btn_checkin@3x.png b/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/map_btn_checkin@3x.png new file mode 100644 index 00000000..f48e4f84 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_checkin.imageset/map_btn_checkin@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/Contents.json new file mode 100644 index 00000000..6966a9ad --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_btn_menu@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_btn_menu@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/map_btn_menu@2x.png b/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/map_btn_menu@2x.png new file mode 100644 index 00000000..76284727 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/map_btn_menu@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/map_btn_menu@3x.png b/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/map_btn_menu@3x.png new file mode 100644 index 00000000..045452d0 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_menu.imageset/map_btn_menu@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/Contents.json new file mode 100644 index 00000000..b2541fca --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_btn_sos@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_btn_sos@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/map_btn_sos@2x.png b/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/map_btn_sos@2x.png new file mode 100644 index 00000000..d08178bc Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/map_btn_sos@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/map_btn_sos@3x.png b/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/map_btn_sos@3x.png new file mode 100644 index 00000000..b0e468c2 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_sos.imageset/map_btn_sos@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/Contents.json new file mode 100644 index 00000000..6da8fbf7 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_btn_trip@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_btn_trip@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/map_btn_trip@2x.png b/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/map_btn_trip@2x.png new file mode 100644 index 00000000..46f48d53 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/map_btn_trip@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/map_btn_trip@3x.png b/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/map_btn_trip@3x.png new file mode 100644 index 00000000..e4dd1d41 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_btn_trip.imageset/map_btn_trip@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/Contents.json new file mode 100644 index 00000000..cbb10f1e --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_circle_icon@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_circle_icon@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/map_circle_icon@2x.png b/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/map_circle_icon@2x.png new file mode 100644 index 00000000..e80fc7a5 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/map_circle_icon@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/map_circle_icon@3x.png b/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/map_circle_icon@3x.png new file mode 100644 index 00000000..c114c82a Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_circle_icon.imageset/map_circle_icon@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/Contents.json new file mode 100644 index 00000000..4cc9a802 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_current_location@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_current_location@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/map_current_location@2x.png b/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/map_current_location@2x.png new file mode 100644 index 00000000..e112af18 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/map_current_location@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/map_current_location@3x.png b/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/map_current_location@3x.png new file mode 100644 index 00000000..ad6ac94c Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_current_location.imageset/map_current_location@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/Contents.json new file mode 100644 index 00000000..d8995016 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_home_indicator@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_home_indicator@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/map_home_indicator@2x.png b/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/map_home_indicator@2x.png new file mode 100644 index 00000000..07acaa2d Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/map_home_indicator@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/map_home_indicator@3x.png b/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/map_home_indicator@3x.png new file mode 100644 index 00000000..606975c5 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_home_indicator.imageset/map_home_indicator@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/Contents.json new file mode 100644 index 00000000..25bb697d --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_member_bubble_large@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_member_bubble_large@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/map_member_bubble_large@2x.png b/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/map_member_bubble_large@2x.png new file mode 100644 index 00000000..02b2ca34 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/map_member_bubble_large@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/map_member_bubble_large@3x.png b/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/map_member_bubble_large@3x.png new file mode 100644 index 00000000..02c94e0f Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_member_bubble_large.imageset/map_member_bubble_large@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/Contents.json new file mode 100644 index 00000000..ef0daa1a --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_member_list_bg@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_member_list_bg@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/map_member_list_bg@2x.png b/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/map_member_list_bg@2x.png new file mode 100644 index 00000000..0441e3f9 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/map_member_list_bg@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/map_member_list_bg@3x.png b/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/map_member_list_bg@3x.png new file mode 100644 index 00000000..6e0dd80a Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_member_list_bg.imageset/map_member_list_bg@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/Contents.json new file mode 100644 index 00000000..fb55bd6f --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_status_icon@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_status_icon@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/map_status_icon@2x.png b/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/map_status_icon@2x.png new file mode 100644 index 00000000..24eb05f6 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/map_status_icon@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/map_status_icon@3x.png b/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/map_status_icon@3x.png new file mode 100644 index 00000000..7d1e91a8 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_status_icon.imageset/map_status_icon@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/Contents.json b/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/Contents.json new file mode 100644 index 00000000..e890d908 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "map_top_panel@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "map_top_panel@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/map_top_panel@2x.png b/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/map_top_panel@2x.png new file mode 100644 index 00000000..f9ffee3d Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/map_top_panel@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/map_top_panel@3x.png b/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/map_top_panel@3x.png new file mode 100644 index 00000000..c04a8178 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Map/map_top_panel.imageset/map_top_panel@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/Contents.json b/QuickLocation/Assets.xcassets/Mine/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/account_security.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/account_security.imageset/Contents.json new file mode 100644 index 00000000..f5f3e1ff --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/account_security.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "account_security@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "account_security@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/account_security.imageset/account_security@2x.png b/QuickLocation/Assets.xcassets/Mine/account_security.imageset/account_security@2x.png new file mode 100644 index 00000000..1882b7d1 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/account_security.imageset/account_security@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/account_security.imageset/account_security@3x.png b/QuickLocation/Assets.xcassets/Mine/account_security.imageset/account_security@3x.png new file mode 100644 index 00000000..1882b7d1 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/account_security.imageset/account_security@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/Contents.json new file mode 100644 index 00000000..3a051b66 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "arrow_right@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "arrow_right@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/arrow_right@2x.png b/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/arrow_right@2x.png new file mode 100644 index 00000000..53cabedb Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/arrow_right@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/arrow_right@3x.png b/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/arrow_right@3x.png new file mode 100644 index 00000000..53cabedb Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/arrow_right.imageset/arrow_right@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/copy.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/copy.imageset/Contents.json new file mode 100644 index 00000000..5045c1b7 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/copy.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "copy@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "copy@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/copy.imageset/copy@2x.png b/QuickLocation/Assets.xcassets/Mine/copy.imageset/copy@2x.png new file mode 100644 index 00000000..5874e1d1 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/copy.imageset/copy@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/copy.imageset/copy@3x.png b/QuickLocation/Assets.xcassets/Mine/copy.imageset/copy@3x.png new file mode 100644 index 00000000..5874e1d1 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/copy.imageset/copy@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/Contents.json new file mode 100644 index 00000000..54d8ae85 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "customer_service@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "customer_service@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/customer_service@2x.png b/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/customer_service@2x.png new file mode 100644 index 00000000..27e045de Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/customer_service@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/customer_service@3x.png b/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/customer_service@3x.png new file mode 100644 index 00000000..27e045de Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/customer_service.imageset/customer_service@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/Contents.json new file mode 100644 index 00000000..b4aaa4dd --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "emergency_contact@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "emergency_contact@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/emergency_contact@2x.png b/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/emergency_contact@2x.png new file mode 100644 index 00000000..d9b3bb04 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/emergency_contact@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/emergency_contact@3x.png b/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/emergency_contact@3x.png new file mode 100644 index 00000000..d9b3bb04 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/emergency_contact.imageset/emergency_contact@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/Contents.json new file mode 100644 index 00000000..3c4bace7 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "header_bg@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "header_bg@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/header_bg@2x.png b/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/header_bg@2x.png new file mode 100644 index 00000000..d6a55d94 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/header_bg@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/header_bg@3x.png b/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/header_bg@3x.png new file mode 100644 index 00000000..d6a55d94 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/header_bg.imageset/header_bg@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/Contents.json new file mode 100644 index 00000000..8aa1b9e2 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "permission_check@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "permission_check@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/permission_check@2x.png b/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/permission_check@2x.png new file mode 100644 index 00000000..cee8825d Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/permission_check@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/permission_check@3x.png b/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/permission_check@3x.png new file mode 100644 index 00000000..cee8825d Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/permission_check.imageset/permission_check@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/Contents.json new file mode 100644 index 00000000..86cc2d80 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "privacy_agreement@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "privacy_agreement@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/privacy_agreement@2x.png b/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/privacy_agreement@2x.png new file mode 100644 index 00000000..f59d85db Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/privacy_agreement@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/privacy_agreement@3x.png b/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/privacy_agreement@3x.png new file mode 100644 index 00000000..f59d85db Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/privacy_agreement.imageset/privacy_agreement@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/Contents.json new file mode 100644 index 00000000..a025acf8 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "profile_bg@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "profile_bg@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/profile_bg@2x.png b/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/profile_bg@2x.png new file mode 100644 index 00000000..6bfa5c77 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/profile_bg@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/profile_bg@3x.png b/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/profile_bg@3x.png new file mode 100644 index 00000000..6bfa5c77 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/profile_bg.imageset/profile_bg@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/Contents.json new file mode 100644 index 00000000..c039e485 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "status_setting@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "status_setting@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/status_setting@2x.png b/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/status_setting@2x.png new file mode 100644 index 00000000..70ac0770 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/status_setting@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/status_setting@3x.png b/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/status_setting@3x.png new file mode 100644 index 00000000..70ac0770 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/status_setting.imageset/status_setting@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/Contents.json b/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/Contents.json new file mode 100644 index 00000000..72471ba6 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "vip_card@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "vip_card@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/vip_card@2x.png b/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/vip_card@2x.png new file mode 100644 index 00000000..d0977228 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/vip_card@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/vip_card@3x.png b/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/vip_card@3x.png new file mode 100644 index 00000000..d0977228 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Mine/vip_card.imageset/vip_card@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/Contents.json new file mode 100644 index 00000000..6e965652 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/Contents.json new file mode 100644 index 00000000..c0113297 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "explore@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "explore@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/explore@2x.png b/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/explore@2x.png new file mode 100644 index 00000000..0e30df29 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/explore@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/explore@3x.png b/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/explore@3x.png new file mode 100644 index 00000000..fe9eac12 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/explore.imageset/explore@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/Contents.json new file mode 100644 index 00000000..29d97e77 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "explore_selected@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "explore_selected@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/explore_selected@2x.png b/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/explore_selected@2x.png new file mode 100644 index 00000000..c64d7465 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/explore_selected@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/explore_selected@3x.png b/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/explore_selected@3x.png new file mode 100644 index 00000000..cbf3018a Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/explore_selected.imageset/explore_selected@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/group.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/group.imageset/Contents.json new file mode 100644 index 00000000..8a443db5 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/group.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "group@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "group@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/group.imageset/group@2x.png b/QuickLocation/Assets.xcassets/Tabbar/group.imageset/group@2x.png new file mode 100644 index 00000000..e94beffe Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/group.imageset/group@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/group.imageset/group@3x.png b/QuickLocation/Assets.xcassets/Tabbar/group.imageset/group@3x.png new file mode 100644 index 00000000..7c476805 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/group.imageset/group@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/Contents.json new file mode 100644 index 00000000..8bf628c9 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "group_selected@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "group_selected@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/group_selected@2x.png b/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/group_selected@2x.png new file mode 100644 index 00000000..c3f33a31 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/group_selected@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/group_selected@3x.png b/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/group_selected@3x.png new file mode 100644 index 00000000..1d15a292 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/group_selected.imageset/group_selected@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/location.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/location.imageset/Contents.json new file mode 100644 index 00000000..d789f58c --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/location.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "location@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "location@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/location.imageset/location@2x.png b/QuickLocation/Assets.xcassets/Tabbar/location.imageset/location@2x.png new file mode 100644 index 00000000..e92c42a7 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/location.imageset/location@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/location.imageset/location@3x.png b/QuickLocation/Assets.xcassets/Tabbar/location.imageset/location@3x.png new file mode 100644 index 00000000..6ccdc54a Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/location.imageset/location@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/Contents.json new file mode 100644 index 00000000..96207449 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "location_selected@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "location_selected@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/location_selected@2x.png b/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/location_selected@2x.png new file mode 100644 index 00000000..a295eacc Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/location_selected@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/location_selected@3x.png b/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/location_selected@3x.png new file mode 100644 index 00000000..3e238e6b Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/location_selected.imageset/location_selected@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/Contents.json new file mode 100644 index 00000000..0623c5ed --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "mine@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "mine@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/mine@2x.png b/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/mine@2x.png new file mode 100644 index 00000000..23e1733d Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/mine@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/mine@3x.png b/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/mine@3x.png new file mode 100644 index 00000000..79249247 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/mine.imageset/mine@3x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/Contents.json b/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/Contents.json new file mode 100644 index 00000000..810295c6 --- /dev/null +++ b/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "mine_selected@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "mine_selected@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/mine_selected@2x.png b/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/mine_selected@2x.png new file mode 100644 index 00000000..f99ab079 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/mine_selected@2x.png differ diff --git a/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/mine_selected@3x.png b/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/mine_selected@3x.png new file mode 100644 index 00000000..141f2c90 Binary files /dev/null and b/QuickLocation/Assets.xcassets/Tabbar/mine_selected.imageset/mine_selected@3x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_1.imageset/Contents.json b/QuickLocation/Assets.xcassets/map_avatar_1.imageset/Contents.json new file mode 100644 index 00000000..098ace08 --- /dev/null +++ b/QuickLocation/Assets.xcassets/map_avatar_1.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "map_avatar_1@2x.png", + "idiom": "universal", + "scale": "2x" + }, + { + "filename": "map_avatar_1@3x.png", + "idiom": "universal", + "scale": "3x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/QuickLocation/Assets.xcassets/map_avatar_1.imageset/map_avatar_1@2x.png b/QuickLocation/Assets.xcassets/map_avatar_1.imageset/map_avatar_1@2x.png new file mode 100644 index 00000000..d025f839 Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_1.imageset/map_avatar_1@2x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_1.imageset/map_avatar_1@3x.png b/QuickLocation/Assets.xcassets/map_avatar_1.imageset/map_avatar_1@3x.png new file mode 100644 index 00000000..653d6b6f Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_1.imageset/map_avatar_1@3x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_2.imageset/Contents.json b/QuickLocation/Assets.xcassets/map_avatar_2.imageset/Contents.json new file mode 100644 index 00000000..7c927218 --- /dev/null +++ b/QuickLocation/Assets.xcassets/map_avatar_2.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "map_avatar_2@2x.png", + "idiom": "universal", + "scale": "2x" + }, + { + "filename": "map_avatar_2@3x.png", + "idiom": "universal", + "scale": "3x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/QuickLocation/Assets.xcassets/map_avatar_2.imageset/map_avatar_2@2x.png b/QuickLocation/Assets.xcassets/map_avatar_2.imageset/map_avatar_2@2x.png new file mode 100644 index 00000000..ca9e0a61 Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_2.imageset/map_avatar_2@2x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_2.imageset/map_avatar_2@3x.png b/QuickLocation/Assets.xcassets/map_avatar_2.imageset/map_avatar_2@3x.png new file mode 100644 index 00000000..9bafe23d Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_2.imageset/map_avatar_2@3x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_3.imageset/Contents.json b/QuickLocation/Assets.xcassets/map_avatar_3.imageset/Contents.json new file mode 100644 index 00000000..d5597212 --- /dev/null +++ b/QuickLocation/Assets.xcassets/map_avatar_3.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "map_avatar_3@2x.png", + "idiom": "universal", + "scale": "2x" + }, + { + "filename": "map_avatar_3@3x.png", + "idiom": "universal", + "scale": "3x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/QuickLocation/Assets.xcassets/map_avatar_3.imageset/map_avatar_3@2x.png b/QuickLocation/Assets.xcassets/map_avatar_3.imageset/map_avatar_3@2x.png new file mode 100644 index 00000000..3033db0e Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_3.imageset/map_avatar_3@2x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_3.imageset/map_avatar_3@3x.png b/QuickLocation/Assets.xcassets/map_avatar_3.imageset/map_avatar_3@3x.png new file mode 100644 index 00000000..ce5f723c Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_3.imageset/map_avatar_3@3x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_4.imageset/Contents.json b/QuickLocation/Assets.xcassets/map_avatar_4.imageset/Contents.json new file mode 100644 index 00000000..dcb0be92 --- /dev/null +++ b/QuickLocation/Assets.xcassets/map_avatar_4.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "map_avatar_4@2x.png", + "idiom": "universal", + "scale": "2x" + }, + { + "filename": "map_avatar_4@3x.png", + "idiom": "universal", + "scale": "3x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/QuickLocation/Assets.xcassets/map_avatar_4.imageset/map_avatar_4@2x.png b/QuickLocation/Assets.xcassets/map_avatar_4.imageset/map_avatar_4@2x.png new file mode 100644 index 00000000..44fbaf9b Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_4.imageset/map_avatar_4@2x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_4.imageset/map_avatar_4@3x.png b/QuickLocation/Assets.xcassets/map_avatar_4.imageset/map_avatar_4@3x.png new file mode 100644 index 00000000..0d472ffe Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_4.imageset/map_avatar_4@3x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_5.imageset/Contents.json b/QuickLocation/Assets.xcassets/map_avatar_5.imageset/Contents.json new file mode 100644 index 00000000..96228098 --- /dev/null +++ b/QuickLocation/Assets.xcassets/map_avatar_5.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "map_avatar_5@2x.png", + "idiom": "universal", + "scale": "2x" + }, + { + "filename": "map_avatar_5@3x.png", + "idiom": "universal", + "scale": "3x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/QuickLocation/Assets.xcassets/map_avatar_5.imageset/map_avatar_5@2x.png b/QuickLocation/Assets.xcassets/map_avatar_5.imageset/map_avatar_5@2x.png new file mode 100644 index 00000000..148f6e80 Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_5.imageset/map_avatar_5@2x.png differ diff --git a/QuickLocation/Assets.xcassets/map_avatar_5.imageset/map_avatar_5@3x.png b/QuickLocation/Assets.xcassets/map_avatar_5.imageset/map_avatar_5@3x.png new file mode 100644 index 00000000..c707c518 Binary files /dev/null and b/QuickLocation/Assets.xcassets/map_avatar_5.imageset/map_avatar_5@3x.png differ diff --git a/QuickLocation/Base.lproj/LaunchScreen.storyboard b/QuickLocation/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..65dc86f5 --- /dev/null +++ b/QuickLocation/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickLocation/Base.lproj/Main.storyboard b/QuickLocation/Base.lproj/Main.storyboard new file mode 100644 index 00000000..25a76385 --- /dev/null +++ b/QuickLocation/Base.lproj/Main.storyboard @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickLocation/Common/Constant.swift b/QuickLocation/Common/Constant.swift new file mode 100644 index 00000000..83ae3c4c --- /dev/null +++ b/QuickLocation/Common/Constant.swift @@ -0,0 +1,137 @@ +// +// Constant.swift +// DLSDK +// +// Created by osell on 2023/3/6. +// + +import Foundation +import SwiftyUserDefaults + +/// NSUserDefaults 常量 +extension DefaultsKeys { + /// 当前经纬度 + var currentLatitude: DefaultsKey { .init("currentLatitude") } + var currentLongitude: DefaultsKey { .init("currentLongitude") } + var currentPlacemark: DefaultsKey { .init("currentPlacemark") } + var currentCity: DefaultsKey { .init("currentCity") } + var currentAreaId: DefaultsKey { .init("currentAreaId", defaultValue: "") } + var currentLevel: DefaultsKey { .init("currentLevel", defaultValue: "") } + var searchLatitude: DefaultsKey { .init("searchLatitude") } + var searchLongitude: DefaultsKey { .init("searchLongitude") } + /// 是否自动更新位置 + var updateLocationEnable: DefaultsKey { .init("updateLocationEnable", defaultValue: true) } + /// 是否从第三方应用跳回 + var isVendorCallback: DefaultsKey { .init("isVendorCallback", defaultValue: false) } + /// 重新登录(IM需要获取id和签名) + var isReLogin: DefaultsKey { .init("isReLogin", defaultValue: false) } + /// 显示引导页 + var guideShowVersion: DefaultsKey { .init("guideShowVersion") } +} + +/// 通知常量 +extension Notification.Name { + /// 重新定位 + static let LocationResetNotification = Notification.Name("LocationResetNotification") + /// 定位更新通知 + static let LocationDidUpdateNotification = Notification.Name("LocationDidUpdateNotification") + /// 位置更换通知 + static let LocationChangeNotification = Notification.Name("LocationChangeNotification") + /// 更换城市通知 + static let CityChangeNotification = Notification.Name("CityChangeNotification") + /// 可滚动通知 + static let IsScrollEnabledNotification = Notification.Name("IsScrollEnabledNotification") + /// 查询订单支付状态 + static let RequestOrderPayStatusNotification = Notification.Name("RequestOrderPayStatusNotification") + /// 跳转物业缴费记录页面 + static let PushRecordNotification = Notification.Name("PushRecordNotification") + /// 显示弹窗 + static let ShowAlertNotification = Notification.Name("ShowAlertNotification") +} + + +// MARK: - 普通常量 +/// KeyWindow +public var kKeyWindow: UIWindow? { UIApplication.keyWindow } +/// KeyWindow安全区域 +public var kSafeAreaInsets: UIEdgeInsets { kKeyWindow?.safeAreaInsets ?? .zero } +/// 屏幕size +public let kScreenSize = UIScreen.main.bounds.size +/// 屏幕宽度 +public let kScreenWidth = UIScreen.main.bounds.size.width +/// 屏幕高度 +public let kScreenHeight = UIScreen.main.bounds.size.height +/// 状态栏高度 +public var kStatusBarHeight: CGFloat { + if #available(iOS 13.0, *) { + let statusBarHeight = UIApplication.shared.windows + .filter { $0.isKeyWindow } + .first? + .windowScene? + .statusBarManager? + .statusBarFrame + .height ?? 0 + return statusBarHeight + } else { + return UIApplication.shared.statusBarFrame.height + } +} +/// 顶部导航+状态栏高度 +public let kNaviHeight = 44 + kStatusBarHeight +/// App显示名称 +public let kAppName = Bundle.main.infoDictionary!["CFBundleDisplayName"] as! String //App 名称 +/// App的Bundle版本 +public let kAppVersion = Bundle.main.infoDictionary!["CFBundleVersion"] as! String //App 版本 +/// App的BundleShort版本 +public let kAppShortVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String +/// App的Identifier +public let kBundleIdentifier = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String + +public let kIsFullScreen = kScreenHeight > 800 ? true : false +public let kSafeBottomMargin: CGFloat = kIsFullScreen ? 34.0 : 0.0 + +/// 每页显示条数 +public let kPageSize = 20 + +/// 同步锁 +/// - Parameters: +/// - lock: 加锁对象 +/// - closure: 执行操作 +public func synchronized(_ lock: Any, closure: () -> ()) { + objc_sync_enter(lock) + closure() + objc_sync_exit(lock) +} + +/// 主线程执行 +/// - Parameter closure: 执行代码 +public func MainAsync(_ closure: (() -> Void)?) { + guard let closure = closure else { return } + Thread.isMainThread ? closure() : DispatchQueue.main.async(execute: closure) +} + +/// 全局队列 +/// - Parameter closure: 执行代码 +public func GlobalAsync(qos: DispatchQoS.QoSClass = .default, _ closure: (() -> Void)?) { + guard let closure = closure else { return } + Thread.isMultiThreaded() ? closure() : DispatchQueue.global(qos: qos).async(execute: closure) +} + +extension DL { + + /// 安全字符串,不为nil + public static func safeString(_ value: Any?) -> String { + guard let value = value, !(value is NSNull) else { return "" } + if let string = value as? String { return string } + if let data = value as? Data { return String(data: data, encoding: .utf8) ?? "" } + if let object = value as? NSObjectProtocol { return object.description } + return String(describing: value) + } + + /// 安全数字,不为nil + public static func safeNumber(_ value: Any?) -> NSNumber { + guard let value = value else { return NSNumber(value: 0) } + if let number = value as? NSNumber { return number } + return safeString(value).number ?? NSNumber(value: 0) + } +} diff --git a/QuickLocation/Common/LogUtils.swift b/QuickLocation/Common/LogUtils.swift new file mode 100644 index 00000000..8a7e0da7 --- /dev/null +++ b/QuickLocation/Common/LogUtils.swift @@ -0,0 +1,38 @@ +// +// LogUtils.swift +// GXM-CRM +// +// Created by Chaosky on 27/10/2017. +// Copyright © 2017 DemoOrg. All rights reserved. +// + +import Foundation +import CocoaLumberjack + +#if DEBUG +public var defaultDebugLevel = DDLogLevel.debug +#else +public var defaultDebugLevel = DDLogLevel.info +#endif + + +public func LogDebug(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { + _DDLogMessage(message(), level: level, flag: .debug, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) +} + + +public func LogInfo(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { + _DDLogMessage(message(), level: level, flag: .info, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) +} + +public func LogWarning(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { + _DDLogMessage(message(), level: level, flag: .warning, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) +} + +public func LogVerbose(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { + _DDLogMessage(message(), level: level, flag: .verbose, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) +} + +public func LogError(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = false, ddlog: DDLog = DDLog.sharedInstance) { + _DDLogMessage(message(), level: level, flag: .error, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) +} diff --git a/QuickLocation/Common/adhoc.xcconfig b/QuickLocation/Common/adhoc.xcconfig new file mode 100644 index 00000000..3824cfd1 --- /dev/null +++ b/QuickLocation/Common/adhoc.xcconfig @@ -0,0 +1,14 @@ +// +// adhoc.xcconfig +// dinoGo +// +// Created by 林 on 2022/11/15. +// Copyright © 2022 dino. All rights reserved. +// + +// Configuration settings file format documentation can be found at: +// https://help.apple.com/xcode/#/dev745c5c974 + +#include "Pods/Target Support Files/Pods-SHECommunity/Pods-SHECommunity.adhoc.xcconfig" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "AdHoc" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) AdHoc=1 diff --git a/QuickLocation/Component/AddImageCell/AddImageCell.swift b/QuickLocation/Component/AddImageCell/AddImageCell.swift new file mode 100644 index 00000000..9796c91c --- /dev/null +++ b/QuickLocation/Component/AddImageCell/AddImageCell.swift @@ -0,0 +1,89 @@ +// +// AddImageCell.swift +// SHECommunity +// +// Created by Lin on 2024/12/23. +// + +import UIKit +import RxSwift +import RxDataSources + +enum ImageUploadItem { + case image(image: UIImage?=nil, imageUrl: String?=nil) + case add +} + +typealias ImageUploadSectionModel = SectionModel + +class AddImageCell: UICollectionViewCell { + + var disposeBag = DisposeBag() + + private func setupSubViews() { + addSubview(bgView) + addSubview(iconView) + addSubview(titleLab) + addSubview(addBtn) + setupLayout() + } + + private func setupLayout() { + bgView.layoutChain.edges() + + iconView.layoutChain + .centerX() + .bottomToCenterYOfView(self, offset: -5) + .width(30) + .heightToWidth(1.0) + + titleLab.layoutChain + .topToBottomOfView(iconView, offset: 5) + .edgesHorzontal() + + addBtn.layoutChain.edges() + } + + lazy var bgView: UIView = { + let view = UIView() + view.cornerRadius = 8 + view.borderWidth = 0.5 + view.borderColor = UIColor(hexStr: "E6E6E6")//ThemeManager.shared.color.lineColor + return view + }() + + lazy var iconView: UIImageView = { + let icon = UIImageView() + icon.image = UIImage(named: "Common/add_photo") + return icon + }() + + lazy var titleLab: UILabel = { + let label = UILabel() + label.text = "添加图片" + label.textColor = ThemeManager.shared.color.titleColor + label.font = .systemFont(ofSize: 12, weight: .regular) + label.textAlignment = .center + return label + }() + + lazy var addBtn: UIButton = { + let button = UIButton (type: .custom) + return button + }() + + override init(frame: CGRect) { + super.init(frame: frame) + contentView.backgroundColor = .clear + setupSubViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func prepareForReuse() { + super.prepareForReuse() + disposeBag = DisposeBag() + } +} diff --git a/QuickLocation/Component/AddImageCell/UploadImageCell.swift b/QuickLocation/Component/AddImageCell/UploadImageCell.swift new file mode 100644 index 00000000..29235b6a --- /dev/null +++ b/QuickLocation/Component/AddImageCell/UploadImageCell.swift @@ -0,0 +1,84 @@ +// +// UploadImageCell.swift +// SHECommunity +// +// Created by Lin on 2024/12/23. +// + +import UIKit +import RxSwift + +class UploadImageCell: UICollectionViewCell { + + var disposeBag = DisposeBag() + + func configure(image: UIImage?=nil, imageUrl: String?=nil) { + if let image = image { + imgView.image = image + } + if let imageUrl = imageUrl { +// playImgView.isHidden = !imageUrl.contains(".mp4") + imgView.dl.setImage(with: imageUrl) + } + } + + private func setupSubViews() { + addSubview(bgView) + bgView.addSubview(imgView) + addSubview(deleteBtn) + + setupLayout() + } + + private func setupLayout() { + bgView.layoutChain + .top(6) + .left() + .right(6) + .bottom() + + imgView.layoutChain.edges() + + deleteBtn.layoutChain + .top() + .right() + .width(18) + .heightToWidth(1.0) + } + + lazy var bgView: UIView = { + let view = UIView() + view.cornerRadius = 8 + view.borderWidth = 0.5 + view.borderColor = UIColor(hexStr: "E6E6E6")//ThemeManager.shared.color.lineColor + view.clipsToBounds = true + return view + }() + + lazy var imgView: UIImageView = { + let view = UIImageView() + view.contentMode = .scaleAspectFill + return view + }() + + lazy var deleteBtn: UIButton = { + let button = UIButton (type: .custom) + button.setImage(UIImage(named: "Common/close_black"), for: .normal) + return button + }() + + override init(frame: CGRect) { + super.init(frame: frame) + contentView.backgroundColor = .clear + setupSubViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func prepareForReuse() { + super.prepareForReuse() + disposeBag = DisposeBag() + } +} diff --git a/QuickLocation/Component/CornerRadiusView/CornerRadiusCell.swift b/QuickLocation/Component/CornerRadiusView/CornerRadiusCell.swift new file mode 100644 index 00000000..b40a613f --- /dev/null +++ b/QuickLocation/Component/CornerRadiusView/CornerRadiusCell.swift @@ -0,0 +1,69 @@ +// +// CornerRadiusCell.swift +// SHECommunity +// +// Created by Lin on 2025/2/19. +// + +import UIKit + +class CornerRadiusCell: UITableViewCell { + + func configure(cornerRad: CGFloat = 16, corners: UIRectCorner = [.topLeft, .topRight]) { + self.corners = corners + self.cornerRad = cornerRad + } + + private var cornerRad: CGFloat = 16 { + didSet { + setNeedsLayout() + } + } + + private var corners: UIRectCorner = [.topLeft, .topRight] + + private func setupSubviews() { + addSubview(cornerRadiusView) + + cornerRadiusView.layoutChain + .edgesVertical() + .edgesHorzontal(10) + .height(15) + } + + lazy var cornerRadiusView: UIView = { + let view = UIView() + view.backgroundColor = .white + return view + }() + + override func layoutSubviews() { + super.layoutSubviews() + cornerRadiusView.setNeedsLayout() + cornerRadiusView.layoutIfNeeded() + cornerRadiusView.setCornerRadius(corners: corners, withCornerRadii: CGSize(width: cornerRad, height: cornerRad)) + } + + override init(style: CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + selectionStyle = .none + backgroundColor = .clear + setupSubviews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + +} diff --git a/QuickLocation/Component/CornerRadiusView/CornerRadiusFooterView.swift b/QuickLocation/Component/CornerRadiusView/CornerRadiusFooterView.swift new file mode 100644 index 00000000..eaf77a56 --- /dev/null +++ b/QuickLocation/Component/CornerRadiusView/CornerRadiusFooterView.swift @@ -0,0 +1,50 @@ +// +// CornerRadiusFooterView.swift +// SHECommunity +// +// Created by Lin on 2024/12/17. +// + +import UIKit + +class CornerRadiusFooterView: UITableViewHeaderFooterView { + + var cornerRad: CGFloat = 16 { + didSet { + setNeedsLayout() + } + } + + private func setupViews() { + addSubview(cornerRadiusView) + + cornerRadiusView.layoutChain +// .bottom(5, relation: .lessThanOrEqual) + .bottom() + .edges(excludingEdge: .bottom) + } + + lazy var cornerRadiusView: UIView = { + let view = UIView() + view.backgroundColor = .white + return view + }() + + override func layoutSubviews() { + super.layoutSubviews() + cornerRadiusView.setNeedsLayout() + cornerRadiusView.layoutIfNeeded() + cornerRadiusView.setCornerRadius(corners: [.bottomLeft, .bottomRight], withCornerRadii: CGSize(width: cornerRad, height: cornerRad)) + } + + override init(reuseIdentifier: String?) { + super.init(reuseIdentifier: reuseIdentifier) + backgroundColor = .clear + setupViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + +} diff --git a/QuickLocation/Component/CornerRadiusView/CornerRadiusHeaderView.swift b/QuickLocation/Component/CornerRadiusView/CornerRadiusHeaderView.swift new file mode 100644 index 00000000..49faa64c --- /dev/null +++ b/QuickLocation/Component/CornerRadiusView/CornerRadiusHeaderView.swift @@ -0,0 +1,49 @@ +// +// CornerRadiusHeaderView.swift +// SHECommunity +// +// Created by Lin on 2024/12/17. +// + +import UIKit + +class CornerRadiusHeaderView: UITableViewHeaderFooterView { + + var cornerRad: CGFloat = 16 { + didSet { + setNeedsLayout() + } + } + + private func setupViews() { + addSubview(cornerRadiusView) + + cornerRadiusView.layoutChain + .top() +// .top(5, relation: .lessThanOrEqual) + .edges(excludingEdge: .top) + } + + lazy var cornerRadiusView: UIView = { + let view = UIView() + view.backgroundColor = .white + return view + }() + + override func layoutSubviews() { + super.layoutSubviews() + cornerRadiusView.setNeedsLayout() + cornerRadiusView.layoutIfNeeded() + cornerRadiusView.setCornerRadius(corners: [.topLeft, .topRight], withCornerRadii: CGSize(width: cornerRad, height: cornerRad)) + } + + override init(reuseIdentifier: String?) { + super.init(reuseIdentifier: reuseIdentifier) + backgroundColor = .clear + setupViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/QuickLocation/Component/ImagePicker/ImagePicker.swift b/QuickLocation/Component/ImagePicker/ImagePicker.swift new file mode 100644 index 00000000..9952f753 --- /dev/null +++ b/QuickLocation/Component/ImagePicker/ImagePicker.swift @@ -0,0 +1,110 @@ +// +// ImagePicker.swift +// HealthyZG +// +// Created by 林 on 2020/6/17. +// Copyright © 2020 Lin. All rights reserved. +// + +import Foundation +import UIKit + +class ImagePicker: NSObject { + /// 选择回调 + var imageDidPicked: ((UIImage) -> Void)? + + /// 拍照相册选择ActionSheet + func presentImagePickerPopup() { + let popup = ImagePickerPopup() + popup.cameraAction = { [weak self] in + guard let self = self else { return } + self.requestCameraAuthorization(delegate: self) + } + popup.albumAction = { [weak self] in + guard let self = self else { return} + self.requestAlbumAuthorization() + } + + UIViewController.presentController(popup, animated: true) + } + + /// 显示相册 + func showCamera() { + requestCameraAuthorization(delegate: self) + } + + /// 显示相机 + func showAlbum() { + requestAlbumAuthorization() + } + + /// 权限:拍照 + func requestCameraAuthorization(delegate: (UIImagePickerControllerDelegate & UINavigationControllerDelegate)) { + Permission.cameraAuthorizationStatus { (status) in + guard status else { + Permission.openAppSetting(title: "", message: String(format: "PermissionCamera".localizedString, kAppName)) + return + } + Permission.photosAuthorizationStatus { (status) in + guard status else { + Permission.openAppSetting(title: "", message: String(format: "PermissionPhotos".localizedString, kAppName)) + return + } + self.presentCameraImagePicker() + } + } + } + + /// 拍照 + func presentCameraImagePicker() { + let imagePickerController = UIImagePickerController() + imagePickerController.sourceType = .camera + imagePickerController.delegate = self + + UIViewController.presentController(imagePickerController, animated: true) +// navigator.present(imagePickerController) + } + + /// 权限:图片选择 + func requestAlbumAuthorization() { + Permission.photosAuthorizationStatus { (status) in + guard status else { + Permission.openAppSetting(title: "", message: String(format: "PermissionPhotos".localizedString, kAppName)) + return + } + self.presentAlbumImagePicker() + } + } + + /// 图片选择 + func presentAlbumImagePicker() { + let imagePickerController = UIImagePickerController() + imagePickerController.sourceType = .photoLibrary + imagePickerController.delegate = self + +// let nav = BaseNavigationController(rootViewController: imagePickerController) +// nav.modalPresentationStyle = .overFullScreen + UIViewController.presentController(imagePickerController, animated: true) +// navigator.present(imagePickerController) + } +} + +extension ImagePicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate { + func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { + guard let type = info[.mediaType] as? String, type == "public.image", + let image = info[.originalImage] as? UIImage else { + picker.dismiss(animated: true, completion: nil) + return + } + DispatchQueue.global().async { +// if let newImage = image.resizeTo(CGSize(width: 1024.0, height: 1024.0), scale: false) { + self.imageDidPicked?(image) +// } + } + picker.dismiss(animated: true, completion: nil) + } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { + picker.dismiss(animated: true, completion: nil) + } +} diff --git a/QuickLocation/Component/ImagePicker/ImagePickerPopup.swift b/QuickLocation/Component/ImagePicker/ImagePickerPopup.swift new file mode 100644 index 00000000..bfb73689 --- /dev/null +++ b/QuickLocation/Component/ImagePicker/ImagePickerPopup.swift @@ -0,0 +1,109 @@ +// +// ImagePickerPopup.swift +// HealthyZG +// +// Created by 林 on 2020/6/17. +// Copyright © 2020 Lin. All rights reserved. +// + +import Foundation +import RxSwift +import SnapKit +import RxCocoa + +class ImagePickerPopup: PopupViewController { + var disposeBag = DisposeBag() + var cameraAction: (() -> Void)? + var albumAction: (() -> Void)? + + init() { + super.init(style: .sheet) + self.addCustomView { contentView in + contentView.backgroundColor = UIColor.white + var cameraButton: UIButton? + if UIImagePickerController.isSourceTypeAvailable(.camera) { + cameraButton = UIButton(type: .system) + cameraButton?.setTitle(NSLocalizedString("拍照", comment: ""), for: .normal) + cameraButton?.titleLabel?.font = .systemFont(ofSize: 16) + cameraButton?.setTitleColor(UIColor(hexStr: "#454545"), for: .normal) + cameraButton?.backgroundColor = UIColor.white + } + if let cameraButton = cameraButton { + contentView.addSubview(cameraButton) +// cameraButton.addBorder(edge: .bottom, width: 0.5, color: UIColor.themeLC2) + } + + let albumButton = UIButton(type: .system) + albumButton.setTitle(NSLocalizedString("相册", comment: ""), for: .normal) + albumButton.titleLabel?.font = .systemFont(ofSize: 16) + albumButton.setTitleColor(UIColor(hexStr: "#454545"), for: .normal) + albumButton.backgroundColor = UIColor.white + contentView.addSubview(albumButton) + + let cancelButton = UIButton(type: .system) + cancelButton.setTitle("取消".localizedString, for: .normal) + cancelButton.titleLabel?.font = .systemFont(ofSize: 16) + cancelButton.setTitleColor(UIColor(hexStr: "#454545"), for: .normal) + cancelButton.backgroundColor = UIColor.white + contentView.addSubview(cancelButton) + + let separatorView = UIView(frame: .zero) + separatorView.backgroundColor = UIColor(hexStr: "#EEEEEE") + contentView.addSubview(separatorView) + + if let cameraButton = cameraButton { + cameraButton.snp.makeConstraints { make in + make.top.left.right.equalToSuperview() + make.height.equalTo(60.0) + } + albumButton.snp.makeConstraints { make in + make.top.equalTo(cameraButton.snp.bottom) + make.left.right.equalToSuperview() + make.height.equalTo(60.0) + } + } else { + albumButton.snp.makeConstraints { make in + make.top.left.right.equalToSuperview() + make.height.equalTo(60.0) + } + } + separatorView.snp.makeConstraints { make in + make.top.equalTo(albumButton.snp.bottom) + make.left.right.equalToSuperview() + make.height.equalTo(10.0) + } + cancelButton.snp.makeConstraints { make in + make.top.equalTo(separatorView.snp.bottom) + make.left.right.equalToSuperview() + if #available(iOS 11.0, *) { + let bottom = UIApplication.keyWindow?.safeAreaInsets.bottom ?? 0 + make.bottom.equalTo(contentView.safeAreaLayoutGuide.snp.bottom).offset(bottom * 0.6) + } else { + make.bottom.equalTo(contentView.snp.bottom) + } + make.height.equalTo(60.0) + } + + cameraButton?.rx.tap.subscribe(onNext: { [weak self] _ in + guard let self = self else { return } + self.hide(callback: { + self.cameraAction?() + }) + }).disposed(by: disposeBag) + + albumButton.rx.tap.subscribe(onNext: { _ in + self.hide(callback: { + self.albumAction?() + }) + }).disposed(by: disposeBag) + + cancelButton.rx.tap.subscribe(onNext: { [weak self] _ in + self?.hide() + }).disposed(by: disposeBag) + } + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/QuickLocation/Component/ImagePicker/PopupAnimator.swift b/QuickLocation/Component/ImagePicker/PopupAnimator.swift new file mode 100644 index 00000000..c5fb3a45 --- /dev/null +++ b/QuickLocation/Component/ImagePicker/PopupAnimator.swift @@ -0,0 +1,92 @@ +// +// PopupAnimator.swift +// JiuLaiBao +// +// Created by SeanXu on 2018/8/5. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import UIKit +import SnapKit + +public protocol PopupViewControllerType { + var grayView: UIView { get set } + var contentView: UIView { get set } + var contentHeight: CGFloat { get set } +} + +public enum PopupAnimatorType { + case present + case dismiss +} + +public class PopupAnimator: NSObject, UIViewControllerAnimatedTransitioning { + + public var animatorType: PopupAnimatorType + + public init(_ animatorType: PopupAnimatorType) { + self.animatorType = animatorType + super.init() + } + + public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + return 0.3 + } + + public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + let containerView = transitionContext.containerView + + guard let fromViewController = transitionContext.viewController(forKey: .from), + let toViewController = transitionContext.viewController(forKey: .to), + let fromView = fromViewController.view, + let toView = toViewController.view else { + print("!!! Error: popup animation is not allowed !!!") + return + } + if animatorType == .present { + guard let popup = toViewController as? PopupViewControllerType else { + return + } + + let grayView = popup.grayView + let contentView = popup.contentView + let duration = transitionDuration(using: transitionContext) + toView.frame = containerView.frame + containerView.addSubview(toView) + toView.layoutIfNeeded() + + grayView.alpha = 0 + contentView.snp.updateConstraints { make in + make.bottom.equalToSuperview() + } + toView.setNeedsUpdateConstraints() + UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { + toView.layoutIfNeeded() + grayView.alpha = 1.0 + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } else if animatorType == .dismiss { + guard let popup = fromViewController as? PopupViewControllerType else { + return + } + + let grayView = popup.grayView + let contentView = popup.contentView + let contentHeight = popup.contentHeight + let duration = transitionDuration(using: transitionContext) + + contentView.snp.updateConstraints { make in + make.bottom.equalTo(contentHeight) + } + fromView.setNeedsUpdateConstraints() + UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { + fromView.layoutIfNeeded() + grayView.alpha = 0 + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } + } + +} diff --git a/QuickLocation/Component/ImagePicker/PopupAnimators.swift b/QuickLocation/Component/ImagePicker/PopupAnimators.swift new file mode 100644 index 00000000..dcfc8363 --- /dev/null +++ b/QuickLocation/Component/ImagePicker/PopupAnimators.swift @@ -0,0 +1,185 @@ +// +// PopupAnimators.swift +// JiuLaiBao +// +// Created by Dan Jiang on 2018/11/14. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import UIKit + +public protocol PopupAnimatable { + var animateOverlayView: UIView { get } + var animateContentView: UIView { get } + var animateWidth: CGFloat { get } + var animateHeight: CGFloat { get } + var animateOverlayAlpha: CGFloat { get } +} + +public extension PopupAnimatable { + var animateWidth: CGFloat { return 0 } + var animateHeight: CGFloat { return 0 } + var animateOverlayAlpha: CGFloat { return 0 } +} + +public class PopupAlertAnimator: NSObject, UIViewControllerAnimatedTransitioning { + + public var isPresented = true + + public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + if isPresented { + return 0.3 + } else { + return 0.15 + } + } + + public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + let containerView = transitionContext.containerView + + var animatedKey: UITransitionContextViewControllerKey = .from + if isPresented { + animatedKey = .to + } + + guard let toViewController = transitionContext.viewController(forKey: .to), + let toView = toViewController.view, + let animatedViewController = transitionContext.viewController(forKey: animatedKey), + let animatable = animatedViewController as? PopupAnimatable else { + print("!!! Error: popup animation is not allowed !!!") + return + } + + let contentView = animatable.animateContentView + if isPresented { + containerView.addSubview(toView) + } + + let duration = transitionDuration(using: transitionContext) + if isPresented { + UIView.animateKeyframes(withDuration: duration, delay: 0, options: [], animations: { + UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: { + contentView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) + }) + UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: { + contentView.transform = .identity + }) + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } else { + UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { + contentView.alpha = 0 + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } + } + +} + +public class PopupSheetAnimator: NSObject, UIViewControllerAnimatedTransitioning { + + public var isPresented = true + + public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + return 0.3 + } + + public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + let containerView = transitionContext.containerView + + var animatedKey: UITransitionContextViewControllerKey = .from + if isPresented { + animatedKey = .to + } + + guard let toViewController = transitionContext.viewController(forKey: .to), + let toView = toViewController.view, + let animatedViewController = transitionContext.viewController(forKey: animatedKey), + let animatable = animatedViewController as? PopupAnimatable else { + print("!!! Error: popup animation is not allowed !!!") + return + } + + let contentView = animatable.animateContentView + if isPresented { + containerView.addSubview(toView) + toView.layoutIfNeeded() + } + + let duration = transitionDuration(using: transitionContext) + let contentViewHeight = contentView.bounds.size.height + let moveOut = CGAffineTransform(translationX: 0, y: contentViewHeight) + if isPresented { + contentView.transform = moveOut + UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { + contentView.transform = .identity + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } else { + UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { + contentView.transform = moveOut + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } + } + +} + +public class PopupScaleAnimator: NSObject, UIViewControllerAnimatedTransitioning { + + public var isPresented = true + + public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + return 0.2 + } + + public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + let containerView = transitionContext.containerView + + var animatedKey: UITransitionContextViewControllerKey = .from + if isPresented { + animatedKey = .to + } + + guard let toViewController = transitionContext.viewController(forKey: .to), + let toView = toViewController.view, + let animatedViewController = transitionContext.viewController(forKey: animatedKey), + let animatable = animatedViewController as? PopupAnimatable else { + print("!!! Error: popup animation is not allowed !!!") + return + } + + let contentView = animatable.animateContentView + let overlayView = animatable.animateOverlayView + let overlayAlpha = animatable.animateOverlayAlpha + if isPresented { + containerView.addSubview(toView) + toView.frame = containerView.bounds + } + + let duration = transitionDuration(using: transitionContext) + if isPresented { + overlayView.alpha = 0 + contentView.transform = CGAffineTransform(scaleX: 0, y: 0) + UIView.animate(withDuration: duration, animations: { + overlayView.alpha = overlayAlpha + contentView.transform = .identity + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } else { + UIView.animate(withDuration: duration, animations: { + overlayView.alpha = 0 + contentView.alpha = 0 + contentView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) + }, completion: { _ in + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + }) + } + } + +} diff --git a/QuickLocation/Component/ImagePicker/PopupViewController+Extension.swift b/QuickLocation/Component/ImagePicker/PopupViewController+Extension.swift new file mode 100644 index 00000000..05ecf555 --- /dev/null +++ b/QuickLocation/Component/ImagePicker/PopupViewController+Extension.swift @@ -0,0 +1,43 @@ +// +// PopupViewController+Extension.swift +// JiuLaiBao +// +// Created by 霹雳火 on 2018/11/21. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import Foundation +import UIKit + +public extension PopupViewController { + convenience init(title: String?, detail: String, + cancelTitle: String?, cancelHandler: ((PopupAction) -> Void)? = nil, + confirmTitle: String?, confirmHandler: ((PopupAction) -> Void)? = nil) { + self.init(style: .alert) + if let title = title { + addHeadline(title) + } + addMessage(detail) + if let cancelTitle = cancelTitle { + addAction(PopupAction(title: cancelTitle, style: .cancel, handler: cancelHandler)) + } + if let confirmTitle = confirmTitle { + addAction(PopupAction(title: confirmTitle, style: .confirm, handler: confirmHandler)) + } + } + + convenience init(title: String?, detail: String, + confirmTitle: String? = "确认", confirmHandler: ((PopupAction) -> Void)? = nil) { + self.init(title: title, detail: detail, + cancelTitle: nil, cancelHandler: nil, + confirmTitle: confirmTitle, confirmHandler: confirmHandler) + } + + convenience init(title: String?, detail: String, + cancelHandler: ((PopupAction) -> Void)?, + confirmHandler: ((PopupAction) -> Void)?) { + self.init(title: title, detail: detail, + cancelTitle: "取消", cancelHandler: cancelHandler, + confirmTitle: "确认", confirmHandler: confirmHandler) + } +} diff --git a/QuickLocation/Component/ImagePicker/PopupViewController.swift b/QuickLocation/Component/ImagePicker/PopupViewController.swift new file mode 100644 index 00000000..c0efb07d --- /dev/null +++ b/QuickLocation/Component/ImagePicker/PopupViewController.swift @@ -0,0 +1,594 @@ +// +// PopupViewController.swift +// JiuLaiBao +// +// Created by Dan Jiang on 2018/11/13. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import UIKit +import SnapKit + +public struct PopupViewConfig { + static public var width: CGFloat = 280 + static public var vMargin: CGFloat = 34 + static public var hMargin: CGFloat = 20 + static public var vSpace: CGFloat = 16 + static public var buttonHeight: CGFloat = 50 + static public var buttonBorderColor = UIColor.gray + static public var closeButtonVMargin: CGFloat = 46 + static public var closeButtonInset: UIEdgeInsets = .init(top: 12, left: 12, bottom: 12, right: 12) + static public var headlineColor = UIColor.black + static public var headlineFont = UIFont.boldSystemFont(ofSize: 17) + static public var messageColor = UIColor.black + static public var messageFont = UIFont.systemFont(ofSize: 17) + static public var confirmColor = UIColor.black + static public var confirmFont = UIFont.boldSystemFont(ofSize: 16) + static public var cancelColor = UIColor.gray + static public var cancelFont = UIFont.boldSystemFont(ofSize: 16) + static public var textFieldHeight: CGFloat = 40 + static public var textFieldBorderColor = UIColor.gray + static public var textFieldTextColor = UIColor.black + static public var textFieldTextFont = UIFont.systemFont(ofSize: 14) + static public var textFieldPlaceholderColor = UIColor.gray + static public var textFieldPlaceholderFont = UIFont.systemFont(ofSize: 14) + static public var textFieldTipsColor = UIColor.red + static public var textFieldTipsFont = UIFont.systemFont(ofSize: 11) + static public var textFieldTipsHMargin: CGFloat = 30 + static public var textFieldTipsVMargin: CGFloat = 6 +} + +public class PopupAction { + + public let image: UIImage? + public let attributedTitle: NSAttributedString? + public let handler: ((PopupAction) -> Void)? + public let autoDismiss: Bool + public let position: Position + + public enum Style { + case confirm + case cancel + } + + public enum Position { + case bottom + case topRight + } + + convenience public init(title: String, style: Style, autoDismiss: Bool = true, handler: ((PopupAction) -> Void)? = nil) { + let attributedTitle: NSAttributedString? + switch style { + case .confirm: + attributedTitle = NSAttributedString(string: title, + attributes: [.font: PopupViewConfig.confirmFont, + .foregroundColor: PopupViewConfig.confirmColor]) + case .cancel: + attributedTitle = NSAttributedString(string: title, + attributes: [.font: PopupViewConfig.cancelFont, + .foregroundColor: PopupViewConfig.cancelColor]) + } + self.init(attributedTitle: attributedTitle, autoDismiss: autoDismiss, handler: handler) + } + + convenience public init(image: UIImage?, autoDismiss: Bool = true, handler: ((PopupAction) -> Void)? = nil) { + self.init(attributedTitle: nil, image: image, position: .topRight, autoDismiss: autoDismiss, handler: handler) + } + + public init(attributedTitle: NSAttributedString?, image: UIImage? = nil, position: Position = .bottom, + autoDismiss: Bool = true, handler: ((PopupAction) -> Void)? = nil) { + self.attributedTitle = attributedTitle + self.image = image + self.position = position + self.autoDismiss = autoDismiss + self.handler = handler + } + +} + +open class PopupViewController: UIViewController { + + public enum Style { + case alert + case sheet + } + + public enum OverlayStyle { + case transparent + case dark + case extraLightBlur + case lightBlur + case darkBlur + } + + public var style: Style { + return inStyle + } + public var overlayStyle: OverlayStyle { + return inOverlayStyle + } + public var headline: String? { + get { + return headlineLabel?.text + } + set { + headlineLabel?.text = newValue + } + } + public var attributedHeadline: NSAttributedString? { + get { + return headlineLabel?.attributedText + } + set { + headlineLabel?.attributedText = newValue + } + } + public var message: String? { + get { + return messageLabel?.text + } + set { + messageLabel?.text = newValue + } + } + public var attributedMessage: NSAttributedString? { + get { + return messageLabel?.attributedText + } + set { + messageLabel?.attributedText = newValue + } + } + public var textField: UITextField? { + return inTextField + } + public var customView: UIView? { + return inCustomView + } + public var actions: [PopupAction] { + return inActions + } + public var presentAnimator: UIViewControllerAnimatedTransitioning? + public var dimsissAnimator: UIViewControllerAnimatedTransitioning? + public var completionCallback: (() -> Void)? + public var canDismissOnOverlay: Bool? + + let inStyle: Style + let inOverlayStyle: OverlayStyle + var inCanDismissOnOverlay = true + var overlayView: UIView! + var contentView: UIView! + var headlineLabel: UILabel? + var messageLabel: UILabel? + var tipsLabel: UILabel? + var inTextField: UITextField? + var inCustomView: UIView? + var actionButtons: [UIButton] = [] + var inActions: [PopupAction] = [] + + required public init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public init(style: Style, overlayStyle: OverlayStyle = .dark) { + self.inStyle = style + self.inOverlayStyle = overlayStyle + super.init(nibName: nil, bundle: nil) + modalPresentationStyle = .overFullScreen + transitioningDelegate = self + } + + deinit { + print("\(self) deinit") + } + + public func addHeadline(_ headline: String) { + let attributedHeadline = NSAttributedString(string: headline, + attributes: [.font: PopupViewConfig.headlineFont, + .foregroundColor: PopupViewConfig.headlineColor]) + addAttributedHeadline(attributedHeadline) + } + + public func addAttributedHeadline(_ headline: NSAttributedString?) { + if headlineLabel == nil { + let label = UILabel() + label.attributedText = headline + headlineLabel = label + } + } + + public func addMessage(_ message: String, alignment: NSTextAlignment = .left) { + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = 6 + paragraphStyle.alignment = alignment + let attributedMessage = NSAttributedString(string: message, + attributes: [.font: PopupViewConfig.messageFont, + .foregroundColor: PopupViewConfig.messageColor, + .paragraphStyle: paragraphStyle]) + addAttributedMessage(attributedMessage) + } + + public func addAttributedMessage(_ message: NSAttributedString?) { + if messageLabel == nil { + let label = UILabel() + label.attributedText = message + label.numberOfLines = 0 + label.lineBreakMode = .byCharWrapping + messageLabel = label + } + } + + public func addTextField(configurationHandler: ((UITextField) -> Void)? = nil) { + if tipsLabel == nil { + tipsLabel = UILabel() + tipsLabel?.textAlignment = .center + } + if inTextField == nil { + let textField = UITextField() + textField.layer.borderColor = PopupViewConfig.textFieldBorderColor.cgColor + textField.layer.borderWidth = 0.5 + textField.textColor = PopupViewConfig.textFieldTextColor + textField.font = PopupViewConfig.textFieldTextFont + let leftView = UIView(frame: .init(x: 0, y: 0, width: 10, + height: PopupViewConfig.textFieldHeight)) + textField.leftView = leftView + textField.leftViewMode = .always + + inTextField = textField + + configurationHandler?(textField) + } + } + + public func setTextFieldPlaceholder(_ placehoder: String?) { + let attributedPlaceholder = NSAttributedString(string: placehoder ?? "", + font: PopupViewConfig.textFieldPlaceholderFont, + color: PopupViewConfig.textFieldPlaceholderColor) + setTextFieldAttributedPlaceholder(attributedPlaceholder) + } + + public func setTextFieldAttributedPlaceholder(_ placehoder: NSAttributedString?) { + inTextField?.attributedPlaceholder = placehoder + } + + public func setTextFieldTips(_ tips: String?) { + let attributedTips = NSAttributedString(string: tips ?? "", + font: PopupViewConfig.textFieldTipsFont, + color: PopupViewConfig.textFieldTipsColor) + setTextFieldAttributedTips(attributedTips) + } + + public func setTextFieldAttributedTips(_ tips: NSAttributedString?) { + tipsLabel?.attributedText = tips + } + + public func addCustomView(configurationHandler: ((UIView) -> Void)) { + if inCustomView == nil { + let customView = UIView() + inCustomView = customView + + configurationHandler(customView) + } + } + + public func addAction(_ action: PopupAction) { + inActions.append(action) + } + + public func hide(callback: (() -> Void)? = nil) { + if let callback = callback { + presentingViewController?.dismiss(animated: true, completion: { + callback() + if let completion = self.completionCallback { + completion() + } + }) + } else { + presentingViewController?.dismiss(animated: true, completion: completionCallback) + } + } + + open override func loadView() { + super.loadView() + } + + open override func viewDidLoad() { + super.viewDidLoad() + + view.backgroundColor = .clear + + if let canDismissOnOverlay = canDismissOnOverlay { + inCanDismissOnOverlay = canDismissOnOverlay + } else { + switch style { + case .alert: + inCanDismissOnOverlay = false + case .sheet: + inCanDismissOnOverlay = true + } + } + + layoutOverlayView() + layoutContentView() + } + + func layoutOverlayView() { + switch overlayStyle { + case .transparent: + overlayView = UIView() + overlayView.backgroundColor = UIColor(white: 0, alpha: 0) + case .dark: + overlayView = UIView() + overlayView.backgroundColor = UIColor(white: 0, alpha: 0.65) + case .extraLightBlur: + let blurEffect = UIBlurEffect(style: .extraLight) + overlayView = UIVisualEffectView(effect: blurEffect) + case .lightBlur: + let blurEffect = UIBlurEffect(style: .light) + overlayView = UIVisualEffectView(effect: blurEffect) + case .darkBlur: + let blurEffect = UIBlurEffect(style: .dark) + overlayView = UIVisualEffectView(effect: blurEffect) + } + + if inCanDismissOnOverlay { + overlayView.isUserInteractionEnabled = true + overlayView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onDismiss))) + } + + view.addSubview(overlayView) + + overlayView.snp.makeConstraints { make in + make.edges.equalToSuperview() + } + } + + func layoutContentView() { + contentView = UIView() + view.addSubview(contentView) + + switch style { + case .alert: + contentView.backgroundColor = .white + contentView.layer.cornerRadius = 2 + contentView.snp.makeConstraints { make in + make.center.equalToSuperview() + make.width.equalTo(PopupViewConfig.width) + } + layoutAlertStyle() + case .sheet: + contentView.snp.makeConstraints { make in + make.left.right.bottom.equalToSuperview() + } + layoutSheetStyle() + } + } + + func layoutAlertStyle() { + var top = PopupViewConfig.vMargin + var actionOnlyInTopRight = true + if actions.contains(where: { $0.position == .topRight }) { + top = PopupViewConfig.closeButtonVMargin + } + if actions.contains(where: { $0.position == .bottom }) { + actionOnlyInTopRight = false + } + + if let headlineLabel = headlineLabel { + contentView.addSubview(headlineLabel) + + headlineLabel.snp.makeConstraints { make in + make.top.equalToSuperview().offset(top) + make.left.equalToSuperview().offset(PopupViewConfig.hMargin) + } + } + + let hLine = UIView() + if !actionOnlyInTopRight { + hLine.backgroundColor = PopupViewConfig.buttonBorderColor + contentView.addSubview(hLine) + hLine.snp.makeConstraints { make in + make.height.equalTo(0.5) + make.right.left.equalToSuperview() + } + } + + if let messageLabel = messageLabel { + contentView.addSubview(messageLabel) + + messageLabel.snp.makeConstraints { make in + if let headlineLabel = headlineLabel { + make.top.equalTo(headlineLabel.snp.bottom).offset(PopupViewConfig.vSpace) + } else { + make.top.equalToSuperview().offset(top) + } + make.left.equalToSuperview().offset(PopupViewConfig.hMargin) + make.right.equalToSuperview().offset(-PopupViewConfig.hMargin) + if !actionOnlyInTopRight { + make.bottom.equalTo(hLine.snp.top).offset(-PopupViewConfig.vMargin) + } else { + make.bottom.equalToSuperview().offset(-PopupViewConfig.vSpace) + } + } + } + + if let textField = inTextField { + contentView.addSubview(textField) + + textField.snp.makeConstraints { make in + if let headlineLabel = headlineLabel { + make.top.equalTo(headlineLabel.snp.bottom).offset(PopupViewConfig.vSpace) + } else { + make.top.equalToSuperview().offset(PopupViewConfig.vMargin) + } + make.left.equalToSuperview().offset(PopupViewConfig.hMargin) + make.right.equalToSuperview().offset(-PopupViewConfig.hMargin) + make.height.equalTo(PopupViewConfig.textFieldHeight) + var tipsHeight: CGFloat = 0 + if tipsLabel != nil { + tipsHeight = 15.0 + } + if !actionOnlyInTopRight { + var bottomOffset = PopupViewConfig.vMargin + tipsHeight + make.bottom.equalTo(hLine.snp.top).offset(-bottomOffset) + } else { + var bottomOffset = PopupViewConfig.vSpace + tipsHeight + make.bottom.equalToSuperview().offset(-bottomOffset) + } + } + + if let tipsLabel = tipsLabel { + contentView.addSubview(tipsLabel) + + tipsLabel.snp.makeConstraints { make in + make.top.equalTo(textField.snp.bottom).offset(PopupViewConfig.textFieldTipsVMargin) + make.left.equalToSuperview().offset(PopupViewConfig.textFieldTipsHMargin) + make.right.equalToSuperview().offset(-PopupViewConfig.textFieldTipsHMargin) + } + } + } + + if let customView = inCustomView { + contentView.addSubview(customView) + + customView.snp.makeConstraints { make in + make.top.left.right.equalToSuperview() + if !actionOnlyInTopRight { + make.bottom.equalTo(hLine.snp.top) + } else { + make.bottom.equalToSuperview() + } + } + } + + var actionsButtonInBottom: [UIButton] = [] + for action in actions { + let button = UIButton() + button.addTarget(self, action: #selector(onTap), for: .touchUpInside) + contentView.addSubview(button) + actionButtons.append(button) + if action.position == .topRight { + button.setImage(action.image, for: .normal) + button.contentEdgeInsets = PopupViewConfig.closeButtonInset + button.snp.makeConstraints { make in + make.top.equalToSuperview() + make.right.equalToSuperview() + } + } else { + button.setAttributedTitle(action.attributedTitle, for: .normal) + actionsButtonInBottom.append(button) + } + } + + var prevButton: UIButton? + for (index, button) in actionsButtonInBottom.enumerated() { + if let prevButton = prevButton { + let vLine = UIView() + vLine.backgroundColor = PopupViewConfig.buttonBorderColor + contentView.addSubview(vLine) + vLine.snp.makeConstraints { make in + make.width.equalTo(0.5) + make.top.equalTo(prevButton) + make.left.equalTo(prevButton.snp.right) + make.bottom.equalToSuperview() + } + button.snp.makeConstraints { make in + make.height.equalTo(PopupViewConfig.buttonHeight) + make.top.equalTo(hLine.snp.bottom) + make.left.equalTo(vLine.snp.right) + make.bottom.equalToSuperview() + make.width.equalTo(prevButton) + if index == actionsButtonInBottom.count - 1 { + make.right.equalToSuperview() + } + } + } else { + button.snp.makeConstraints { make in + make.height.equalTo(PopupViewConfig.buttonHeight) + make.top.equalTo(hLine.snp.bottom) + make.left.equalToSuperview() + make.bottom.equalToSuperview() + if index == actionsButtonInBottom.count - 1 { + make.right.equalToSuperview() + } + } + } + prevButton = button + } + + } + + func layoutSheetStyle() { + if let customView = inCustomView { + contentView.addSubview(customView) + + customView.snp.makeConstraints { make in + make.edges.equalToSuperview() + } + } + } + + @objc func onDismiss() { + hide() + } + + @objc func onTap(button: UIButton) { + if let index = actionButtons.firstIndex(where: { $0 == button }) { + let action = actions[index] + if action.autoDismiss { + hide { + if let handler = action.handler { + handler(action) + } + } + } else { + if let handler = action.handler { + handler(action) + } + } + } + } + +} + +extension PopupViewController: UIViewControllerTransitioningDelegate { + + public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { + if let presentAnimator = presentAnimator { + return presentAnimator + } else if style == .alert { + return PopupAlertAnimator() + } else if style == .sheet { + return PopupSheetAnimator() + } + return nil + } + + public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { + if let dimsissAnimator = dimsissAnimator { + return dimsissAnimator + } else if style == .alert { + let animator = PopupAlertAnimator() + animator.isPresented = false + return animator + } else if style == .sheet { + let animator = PopupSheetAnimator() + animator.isPresented = false + return animator + } + return nil + } + +} + +extension PopupViewController: PopupAnimatable { + + public var animateContentView: UIView { + return contentView + } + + public var animateOverlayView: UIView { + return overlayView + } + +} diff --git a/QuickLocation/Component/TextTableViewCell/TextArrowCell.swift b/QuickLocation/Component/TextTableViewCell/TextArrowCell.swift new file mode 100644 index 00000000..30353908 --- /dev/null +++ b/QuickLocation/Component/TextTableViewCell/TextArrowCell.swift @@ -0,0 +1,96 @@ +// +// TextArrowCell.swift +// SHECommunity +// +// Created by Lin on 2025/1/7. +// + +import UIKit + +struct TextCellModel { + var title: String + var content: String?=nil + var routeUrl: String +} + +/// 标题+箭头 +class TextArrowCell: UITableViewCell { + + func configure(model: TextCellModel) { + titleLab.text = model.title + contentLab.text = model.content.safeString + } + + private func setupSubviews() { + contentView.addSubview(bgView) + bgView.addSubview(titleLab) + bgView.addSubview(contentLab) + bgView.addSubview(arrowIconView) + + bgView.layoutChain + .top() + .edgesHorzontal(10) + .bottom(10) + + titleLab.layoutChain + .edgesHorzontal(12) + .edgesVertical(15) + + arrowIconView.layoutChain + .right(12) + .centerY() + + contentLab.layoutChain + .rightToLeftOfView(arrowIconView) + .centerY() + } + + lazy var bgView: UIView = { + let view = UIView() + view.backgroundColor = .white + view.cornerRadius = 8 + return view + }() + + lazy var titleLab: UILabel = { + let label = UILabel() + label.textColor = ThemeManager.shared.color.titleColor + label.font = .systemFont(ofSize: 15, weight: .regular) + return label + }() + + lazy var contentLab: UILabel = { + let label = UILabel() + label.textColor = ThemeManager.shared.color.contentColor + label.font = .systemFont(ofSize: 13, weight: .regular) + return label + }() + + lazy var arrowIconView: UIImageView = { + let imgView = UIImageView() + imgView.image = UIImage(named: "Common/arrow_black") + return imgView + }() + + override init(style: CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + selectionStyle = .none + backgroundColor = .clear + setupSubviews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } +} diff --git a/QuickLocation/Component/TextTableViewCell/TextContentArrowCell.swift b/QuickLocation/Component/TextTableViewCell/TextContentArrowCell.swift new file mode 100644 index 00000000..50205b9e --- /dev/null +++ b/QuickLocation/Component/TextTableViewCell/TextContentArrowCell.swift @@ -0,0 +1,95 @@ +// +// TextContentArrowCell.swift +// SHECommunity +// +// Created by Lin on 2025/1/7. +// + +import UIKit + +/// 标题+内容+箭头 +class TextContentArrowCell: UITableViewCell { + + func configure(model: TextCellModel) { + titleLab.text = model.title + contentLab.text = model.content + } + + private func setupSubviews() { + contentView.addSubview(bgView) + bgView.addSubview(titleLab) + bgView.addSubview(contentLab) + bgView.addSubview(arrowIconView) + + bgView.layoutChain + .top() + .edgesHorzontal(10) + .bottom(10) + + titleLab.layoutChain + .top(12) + .left(12) + .bottomToCenterYOfView(bgView, offset: 2) + + contentLab.layoutChain + .leftToView(titleLab) + .topToCenterYOfView(bgView, offset: 2) + .bottom(14) + + arrowIconView.layoutChain + .right(12) + .centerY() + } + + lazy var bgView: UIView = { + let view = UIView() + view.backgroundColor = .white + view.cornerRadius = 8 + return view + }() + + lazy var titleLab: UILabel = { + let label = UILabel() + label.textColor = ThemeManager.shared.color.titleColor + label.font = .systemFont(ofSize: 15, weight: .regular) + label.numberOfLines = 0 + return label + }() + + lazy var contentLab: UILabel = { + let label = UILabel() + label.textColor = ThemeManager.shared.color.contentColor + label.font = .systemFont(ofSize: 12, weight: .regular) + label.numberOfLines = 0 + return label + }() + + lazy var arrowIconView: UIImageView = { + let imgView = UIImageView() + imgView.image = UIImage(named: "Common/arrow_black") + return imgView + }() + + override init(style: CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + selectionStyle = .none + backgroundColor = .clear + setupSubviews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + +} diff --git a/QuickLocation/Component/TextTableViewCell/TextTableViewCell.swift b/QuickLocation/Component/TextTableViewCell/TextTableViewCell.swift new file mode 100644 index 00000000..72916ef2 --- /dev/null +++ b/QuickLocation/Component/TextTableViewCell/TextTableViewCell.swift @@ -0,0 +1,54 @@ +// +// TextTableViewCell.swift +// SHECommunity +// +// Created by 林 on 2024/12/5. +// + +import UIKit + +/// 标题 +class TextTableViewCell: UITableViewCell { + + func configure(text: String) { + titleLab.text = text + } + + override init(style: CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + selectionStyle = .none + backgroundColor = .clear + setupSubviews() + } + + private func setupSubviews() { + contentView.addSubview(titleLab) + + titleLab.layoutChain + .edgesHorzontal(12) + .edgesVertical(8) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + + lazy var titleLab: UILabel = { + let label = UILabel() + label.textColor = ThemeManager.shared.color.titleColor + label.font = .systemFont(ofSize: 14, weight: .medium) + label.numberOfLines = 0 + return label + }() +} diff --git a/QuickLocation/Core/Extension/Array+Extension.swift b/QuickLocation/Core/Extension/Array+Extension.swift new file mode 100755 index 00000000..f5fb0f96 --- /dev/null +++ b/QuickLocation/Core/Extension/Array+Extension.swift @@ -0,0 +1,82 @@ +// +// Array+Extension.swift +// PaiLiBo +// +// Created by SeanXu on 2019/10/25. +// Copyright © 2019 GuoXiaoMei. All rights reserved. +// + +import Foundation + +extension Sequence { + func group(by key: (Iterator.Element) throws -> GroupingType) rethrows -> [[Iterator.Element]] { + try reduce(into: []) { result, element in + if let lastElement = result.last?.last, try key(lastElement) == key(element) { + result[result.index(before: result.endIndex)].append(element) + } else { + result.append([element]) + } + } + } +} + +extension Array where Element: Equatable { + + public mutating func removeObject(_ object : Iterator.Element) { + if let index = firstIndex(of: object) { + remove(at: index) + } + } + + public mutating func insertObject(_ object : Iterator.Element) { + if let _ = firstIndex(of: object) { + return + } else { + append(object) + } + } + + public func toJsonArray() -> String{ + + guard self.count > 0 else { + return "" + } + + let mutaleSting:NSMutableString = "[" + for (index,obj) in self.enumerated(){ + if obj is String{ + mutaleSting.append("\"") + mutaleSting.append(obj as! String) + mutaleSting.append("\"") + if index < self.count - 1{ + mutaleSting.append(",") + } + if index == self.count-1 { + mutaleSting.append("]") + } + } + } + return mutaleSting as String + } + + public func dicArrayToJsonString() -> String { + if (!JSONSerialization.isValidJSONObject(self)) { + print("无法解析出JSONString") + return " " + } + if let data = try? JSONSerialization.data(withJSONObject: self, options: []), let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) as String? { + return JSONString + } + return " " + } +} + +extension Array { + public static var safeValue: Array { return [] } + public func safeElement(_ index: Int) -> Element? { + return index >= 0 && index < endIndex ? self[index] : nil + } + public subscript(safe index: Int) -> Element? { + return safeElement(index) + } +} diff --git a/QuickLocation/Core/Extension/ControlEvents+Block.swift b/QuickLocation/Core/Extension/ControlEvents+Block.swift new file mode 100644 index 00000000..d916492c --- /dev/null +++ b/QuickLocation/Core/Extension/ControlEvents+Block.swift @@ -0,0 +1,230 @@ +// +// Block.swift +// DLSDK +// +// Created by osell on 2023/3/6. +// + +import UIKit +import ObjectiveC.runtime + +public typealias VoidAnyBlock = (Any) -> Void + +class InnerBlockTarget: NSObject { + + var identifier: String = "" + var block: VoidAnyBlock? + var events: UIControl.Event? + + override init() { + self.identifier = UUID().uuidString + super.init() + } + + @objc + func invoke(_ sender: Any) { + if let block = block { + block(sender) + } + } + +} + +// MARK: - UIGestureRecognizer + Block +@objc extension UIGestureRecognizer { + + struct BlockKey { + static var innerBlockTargets = "innerBlockTargets" + } + + var innerBlockTargets: [InnerBlockTarget] { + get { + guard let targets = objc_getAssociatedObject(self, &BlockKey.innerBlockTargets) as? [InnerBlockTarget] else { + return [] + } + return targets + } + + set { + objc_setAssociatedObject(self, &BlockKey.innerBlockTargets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// 增加Tap + /// - Parameter block: 事件回调 + /// - Returns: UIGestureRecognizer + @discardableResult + public class func gestureRecognizer(with block: @escaping VoidAnyBlock) -> UIGestureRecognizer { + let gestureRecognizer = UIGestureRecognizer() + gestureRecognizer.addBlock(block) + return gestureRecognizer + } + + /// 增加Block + @discardableResult + public func addBlock(_ block: @escaping VoidAnyBlock) -> String { + let target = InnerBlockTarget() + target.block = block + addTarget(target, action: #selector(InnerBlockTarget.invoke(_:))) + var targets = innerBlockTargets + targets.append(target) + innerBlockTargets = targets + return target.identifier + } + + /// 删除Block + public func removeBlock(identifier: String) { + if identifier.isEmpty { return } + var targets = innerBlockTargets + guard let target = targets.first(where: { $0.identifier == identifier }) else { return } + removeTarget(target, action: #selector(InnerBlockTarget.invoke(_:))) + targets.removeObject(target) + innerBlockTargets = targets + } + + /// 删除全部 + public func removeAll() { + innerBlockTargets.forEach { + self.removeTarget($0, action: #selector(InnerBlockTarget.invoke(_:))) + } + innerBlockTargets = [] + } +} + +// MARK: - UIView + Block +@objc extension UIView { + + struct BlockKey { + static var addTapGestrueBlock = "addTapGestrueBlock" + } + + /// UIView添加Tap点击事件 + /// - Parameters: + /// - taget: Any + /// - action: Selector + public func addTapGestrue(with taget: Any, action: Selector?) { + let tap = UITapGestureRecognizer(target: taget, action: action) + isUserInteractionEnabled = true + addGestureRecognizer(tap) + } + + /// UIView添加Tap点击事件 + /// - Parameter block: 点击Block回调 + /// - Returns: indetifier + @discardableResult + public func addTapGestrue(block: @escaping VoidAnyBlock) -> String { + let tap = UITapGestureRecognizer() + let indetifier = tap.addBlock(block) + objc_setAssociatedObject(tap, &BlockKey.addTapGestrueBlock, indetifier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + isUserInteractionEnabled = true + addGestureRecognizer(tap) + return indetifier + } + + /// 移除Tap事件 + /// - Parameter identifier: identifier + public func removeTapGestrueBlock(with identifier: String) { + if identifier.isEmpty { return } + gestureRecognizers?.forEach { + if $0.isKind(of: UITapGestureRecognizer.self), + let tempidentifier = objc_getAssociatedObject($0, &BlockKey.addTapGestrueBlock) as? String, + tempidentifier == identifier { + $0.removeBlock(identifier: identifier) + self.removeGestureRecognizer($0) + } + } + } +} + +// MARK: - UIControl + Block +@objc extension UIControl { + + struct BlockKey { + static var innerBlockTargets = "innerBlockTargets" + } + + var innerBlockTargets: [InnerBlockTarget] { + get { + guard let targets = objc_getAssociatedObject(self, &BlockKey.innerBlockTargets) as? [InnerBlockTarget] else { + return [] + } + return targets + } + + set { + objc_setAssociatedObject(self, &BlockKey.innerBlockTargets, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// 添加block的ControlEvents + /// - Parameters: + /// - controlEvents: UIControl.Event + /// - block: (Any) -> Void + /// - Returns: identifier + @discardableResult + public func addBlock(for controlEvents: UIControl.Event, + block: @escaping VoidAnyBlock) -> String { + if let target = innerBlockTargets.first(where: { $0.events == controlEvents }) { + innerBlockTargets.removeObject(target) + } + let target = InnerBlockTarget() + target.block = block + target.events = controlEvents + addTarget(target, action: #selector(InnerBlockTarget.invoke(_:)), for: controlEvents) + var targets = innerBlockTargets + targets.append(target) + innerBlockTargets = targets + return target.identifier + } + + + /// 移除Block + /// - Parameters: + /// - controlEvents: UIControl.Event + /// - identifier: identifier + public func removeBlock(for controlEvents: UIControl.Event, identifier: String) { + if identifier.isEmpty { return } + removeAllBlock(for: controlEvents, identifier: identifier) + } + + /// 移除identifier全部Block + /// - Parameters: + /// - controlEvents: UIControl.Event + /// - identifier: identifier, 默认为空,会移除所有的block + public func removeAllBlock(for controlEvents: UIControl.Event, identifier: String = "") { + var targets = innerBlockTargets + var removes = [InnerBlockTarget]() + targets.forEach { + if let events = $0.events, + ((events.rawValue & controlEvents.rawValue) != 0), + ($0.identifier == identifier || identifier.isEmpty) { + let event = UIControl.Event(rawValue: events.rawValue & (~controlEvents.rawValue)) + if event.rawValue != 0 { + removeTarget($0, action: #selector(InnerBlockTarget.invoke(_:)), for: controlEvents) + $0.events = event + addTarget($0, action: #selector(InnerBlockTarget.invoke(_:)), for: event) + } else { + removeTarget($0, action: #selector(InnerBlockTarget.invoke(_:)), for: controlEvents) + removes.append($0) + } + } + } + removes.forEach { + targets.removeObject($0) + } + innerBlockTargets = targets + } + + public func addTouchTarget(_ target: Any, action: Selector) { + addTarget(target, action: action, for: .touchUpInside) + } + + @discardableResult + public func addTouchBlock(_ block: @escaping VoidAnyBlock) -> String { + addBlock(for: .touchUpInside, block: block) + } + + public func removeTouchBlock(with identifier: String) { + removeBlock(for: .touchUpInside, identifier: identifier) + } +} diff --git a/QuickLocation/Core/Extension/Date+Extension.swift b/QuickLocation/Core/Extension/Date+Extension.swift new file mode 100644 index 00000000..94a97317 --- /dev/null +++ b/QuickLocation/Core/Extension/Date+Extension.swift @@ -0,0 +1,16 @@ +// +// Date+Extension.swift +// SHECommunity +// +// Created by Lin on 2024/12/23. +// + +import Foundation + +extension Date { + func formatterStyle(_ style: String) -> String { + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = style + return dateFormatter.string(from: self) + } +} diff --git a/QuickLocation/Core/Extension/Dictionay+Extension.swift b/QuickLocation/Core/Extension/Dictionay+Extension.swift new file mode 100644 index 00000000..f52a8395 --- /dev/null +++ b/QuickLocation/Core/Extension/Dictionay+Extension.swift @@ -0,0 +1,18 @@ +// +// Dictionay+Extension.swift +// dinoGo +// +// Created by 林 on 2022/3/15. +// Copyright © 2022 dino. All rights reserved. +// + +import Foundation + +public extension Dictionary { + func toJsonString() -> String { + let data = try? JSONSerialization.data(withJSONObject: self, + options: JSONSerialization.WritingOptions.init(rawValue: 0)) + let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) + return jsonStr! as String + } +} diff --git a/QuickLocation/Core/Extension/Int+Extension.swift b/QuickLocation/Core/Extension/Int+Extension.swift new file mode 100644 index 00000000..cd40c2f3 --- /dev/null +++ b/QuickLocation/Core/Extension/Int+Extension.swift @@ -0,0 +1,67 @@ +// +// Int+Extension.swift +// dinoGo +// +// Created by Lin on 2022/9/23. +// Copyright © 2022 dino. All rights reserved. +// + +import Foundation +//import + +public extension Int { + func timeStampToString(_ timeValue: (_ day: Int, + _ hour: Int, + _ minute: Int, + _ second: Int) -> String) -> String { + ///天 + let days = Int(self / (3600*24)) + ///时 + let hours = Int((self - days*24*3600)/3600) + ///分 + let minute = Int((self - days*24*3600-hours*3600)/60) + ///秒 + let second = Int((self - days*24*3600-hours*3600) - 60*minute) + return timeValue(days, hours, minute, second) + } + + /// 时分秒 + func timeStampToHHSS() -> String { + ///时 + let hours = Int(self/3600) + ///分 + let minute = Int(self%3600/60) + ///秒 + let second = Int(self%60) + let timeString = String.init(format: "%02d:%02d:%02d", hours, minute, second) + return timeString + } + + /// 分秒 + func timeStampToMMSS() -> String { + ///分 + let minute = Int(self%3600/60) + ///秒 + let second = Int(self%60) + let timeString = String.init(format: "%02d:%02d", minute, second) + return timeString + } +} + +// MARK: - File Size +public extension Int64 { + /// 文件大小size, 是以kb单位为最低数值 + var sizeValue: String { + if self < 0 { return "0kb" } + switch self { + case 0..<1024: + return String(format: "%dkb", self) + case 1024..<(1024 << 10): + return String(format: "%.2fM", CGFloat(self) / CGFloat(1024)) + case (1024 << 10)..<(1024 << 20): + return String(format: "%.2fG", CGFloat(self) / CGFloat(1024 << 10)) + default: + return String(format: "%.2fT", CGFloat(self) / CGFloat(1024 << 20)) + } + } +} diff --git a/QuickLocation/Core/Extension/NSAttributedString+Extension.swift b/QuickLocation/Core/Extension/NSAttributedString+Extension.swift new file mode 100644 index 00000000..3a489fa8 --- /dev/null +++ b/QuickLocation/Core/Extension/NSAttributedString+Extension.swift @@ -0,0 +1,44 @@ +// +// NSAttributedString+Extension.swift +// JiuLaiBao +// +// Created by SeanXu on 17/05/2018. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import Foundation +import UIKit + +public extension NSAttributedString { + + convenience init?(string: String?, fontSize: CGFloat, color: UIColor = UIColor.darkText) { + self.init(string: string, font: UIFont.systemFont(ofSize: fontSize), color: color) + } + + convenience init?(string: String?, font: UIFont, color: UIColor) { + guard let string = string else { return nil } + let attributes: [NSAttributedString.Key: Any] = [ + .font: font, + .foregroundColor: color + ] + self.init(string: string, attributes: attributes) + } + + convenience init?(string: String?, fontSize: CGFloat, color: UIColor = UIColor.darkText, lineSpacing: CGFloat) { + self.init(string: string, font: UIFont.systemFont(ofSize: fontSize), color: color, lineSpacing: lineSpacing) + } + + convenience init?(string: String?, font: UIFont, color: UIColor, lineSpacing: CGFloat) { + guard let string = string else { return nil } + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = lineSpacing + let attributes: [NSAttributedString.Key: Any] = [ + .paragraphStyle: paragraphStyle, + .font: font, + .foregroundColor: color, + .baselineOffset: 0 + ] + self.init(string: string, attributes: attributes) + } + +} diff --git a/QuickLocation/Core/Extension/ObjectMapper+Extension.swift b/QuickLocation/Core/Extension/ObjectMapper+Extension.swift new file mode 100644 index 00000000..2da5b10f --- /dev/null +++ b/QuickLocation/Core/Extension/ObjectMapper+Extension.swift @@ -0,0 +1,36 @@ +// +// ObjectMapper+Extension.swift +// DLSDK +// +// Created by osell on 2023/4/7. +// + +import ObjectMapper + +public extension Mappable { + + init?(data: Data, context: MapContext? = nil) { + guard let dataStr = String(data: data, encoding: .utf8) else { + return nil + } + self.init(JSONString: dataStr, context: context) + } + + func toData(prettyPrint: Bool = false) -> Data? { + toJSONString(prettyPrint: prettyPrint)?.data(using: .utf8) + } +} + +public extension Array where Element: BaseMappable { + + init?(data: Data, context: MapContext? = nil) { + guard let dataStr = String(data: data, encoding: .utf8) else { + return nil + } + self.init(JSONString: dataStr) + } + + func toData(prettyPrint: Bool = false) -> Data? { + toJSONString(prettyPrint: prettyPrint)?.data(using: .utf8) + } +} diff --git a/QuickLocation/Core/Extension/Optional+Extension.swift b/QuickLocation/Core/Extension/Optional+Extension.swift new file mode 100644 index 00000000..dbe6b5fa --- /dev/null +++ b/QuickLocation/Core/Extension/Optional+Extension.swift @@ -0,0 +1,21 @@ +// +// Optional+Extension.swift +// DLSDK +// +// Created by osell on 2023/6/9. +// + +import Foundation + +/// 可选类安全转换,不为nil +extension Optional { + public var safeInt: Int { safeNumber.intValue } + public var safeBool: Bool { safeNumber.boolValue } + public var safeFloat: Float { safeNumber.floatValue } + public var safeDouble: Double { safeNumber.doubleValue } + public var safeString: String { DL.safeString(self) } + public var safeNumber: NSNumber { DL.safeNumber(self) } + public var safeArray: [Any] { (self as? [Any]) ?? [] } + public var safeDictionary: [AnyHashable: Any] { (self as? [AnyHashable: Any]) ?? [:] } +} + diff --git a/QuickLocation/Core/Extension/RTL/UIButton+RTL.h b/QuickLocation/Core/Extension/RTL/UIButton+RTL.h new file mode 100644 index 00000000..be5df171 --- /dev/null +++ b/QuickLocation/Core/Extension/RTL/UIButton+RTL.h @@ -0,0 +1,16 @@ +// +// UIButton+RTL.h +// DLSDK +// +// Created by osell on 2023/8/21. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface UIButton (RTL) + +@end + +NS_ASSUME_NONNULL_END diff --git a/QuickLocation/Core/Extension/RTL/UIButton+RTL.m b/QuickLocation/Core/Extension/RTL/UIButton+RTL.m new file mode 100644 index 00000000..42f6f6c1 --- /dev/null +++ b/QuickLocation/Core/Extension/RTL/UIButton+RTL.m @@ -0,0 +1,56 @@ +// +// UIButton+RTL.m +// DLSDK +// +// Created by osell on 2023/8/21. +// + +#import "UIButton+RTL.h" +#import + +UIEdgeInsets RTLEdgeInsetsWithInsets(UIEdgeInsets insets) { + if (insets.left != insets.right) { + CGFloat temp = insets.left; + insets.left = insets.right; + insets.right = temp; + } + return insets; +} + +@implementation UIButton (RTL) + ++ (void)load{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Method oldMethod = class_getInstanceMethod(self, @selector(setContentEdgeInsets:)); + Method newMethod = class_getInstanceMethod(self, @selector(rtl_setContentEdgeInsets:)); + method_exchangeImplementations(oldMethod, newMethod); + + Method oldImageMethod = class_getInstanceMethod(self, @selector(setImageEdgeInsets:)); + Method newImageMethod = class_getInstanceMethod(self, @selector(rtl_setImageEdgeInsets:)); + method_exchangeImplementations(oldImageMethod,newImageMethod); + + Method oldTitleMethod = class_getInstanceMethod(self, @selector(setTitleEdgeInsets:)); + Method newTitleMethod = class_getInstanceMethod(self, @selector(rtl_setTitleEdgeInsets:)); + method_exchangeImplementations(oldTitleMethod,newTitleMethod); + }); +} + +- (void)rtl_setContentEdgeInsets:(UIEdgeInsets)contentEdgeInsets { + + UIEdgeInsets insets = [UIView appearance].semanticContentAttribute == UISemanticContentAttributeForceRightToLeft ? RTLEdgeInsetsWithInsets(contentEdgeInsets) : contentEdgeInsets; + [self rtl_setContentEdgeInsets:insets]; +} + +- (void)rtl_setImageEdgeInsets:(UIEdgeInsets)imageEdgeInsets { + + UIEdgeInsets insets = [UIView appearance].semanticContentAttribute == UISemanticContentAttributeForceRightToLeft ? RTLEdgeInsetsWithInsets(imageEdgeInsets) : imageEdgeInsets; + [self rtl_setImageEdgeInsets:insets]; +} + +- (void)rtl_setTitleEdgeInsets:(UIEdgeInsets)titleEdgeInsets { + UIEdgeInsets insets = [UIView appearance].semanticContentAttribute == UISemanticContentAttributeForceRightToLeft ? RTLEdgeInsetsWithInsets(titleEdgeInsets) : titleEdgeInsets; + [self rtl_setTitleEdgeInsets:insets]; +} + +@end diff --git a/QuickLocation/Core/Extension/Response+ObjectMapper.swift b/QuickLocation/Core/Extension/Response+ObjectMapper.swift new file mode 100755 index 00000000..9bd10e44 --- /dev/null +++ b/QuickLocation/Core/Extension/Response+ObjectMapper.swift @@ -0,0 +1,94 @@ +// +// Observable+ObjectMapper.swift +// +// Created by Ivan Bruel on 09/12/15. +// Copyright © 2015 Ivan Bruel. All rights reserved. +// + +import Foundation +import Moya +import ObjectMapper + +public extension Response { + + /// Maps data received from the signal into an object which implements the Mappable protocol. + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, context: MapContext? = nil) throws -> T { + guard let object = Mapper(context: context).map(JSONObject: try mapJSON()) else { + throw MoyaError.jsonMapping(self) + } + return object + } + + /// Maps data received from the signal into an array of objects which implement the Mappable + /// protocol. + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, context: MapContext? = nil) throws -> [T] { + guard let array = try mapJSON() as? [[String: Any]] else { + throw MoyaError.jsonMapping(self) + } + return Mapper(context: context).mapArray(JSONArray: array) + } + + /// Maps data received from the signal into an object which implements the Mappable protocol. + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) throws -> T { + guard let object = Mapper(context: context).map(JSONObject: (try mapJSON() as? NSDictionary)?.value(forKeyPath: keyPath)) else { + throw MoyaError.jsonMapping(self) + } + return object + } + + /// Maps data received from the signal into an array of objects which implement the Mappable + /// protocol. + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, atKeyPath keyPath: String, context: MapContext? = nil) throws -> [T] { + guard let array = (try mapJSON() as? NSDictionary)?.value(forKeyPath: keyPath) as? [[String: Any]] else { + throw MoyaError.jsonMapping(self) + } + return Mapper(context: context).mapArray(JSONArray: array) + } +} + +// MARK: - ImmutableMappable + +public extension Response { + + /// Maps data received from the signal into an object which implements the ImmutableMappable + /// protocol. + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, context: MapContext? = nil) throws -> T { + return try Mapper(context: context).map(JSONObject: try mapJSON()) + } + + /// Maps data received from the signal into an array of objects which implement the ImmutableMappable + /// protocol. + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, context: MapContext? = nil) throws -> [T] { + guard let array = try mapJSON() as? [[String: Any]] else { + throw MoyaError.jsonMapping(self) + } + return try Mapper(context: context).mapArray(JSONArray: array) + } + + /// Maps data received from the signal into an object which implements the ImmutableMappable + /// protocol. + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) throws -> T { + guard let object = Mapper(context: context).map(JSONObject: (try mapJSON() as? NSDictionary)?.value(forKeyPath: keyPath)) else { + throw MoyaError.jsonMapping(self) + } + return object + } + + /// Maps data received from the signal into an array of objects which implement the ImmutableMappable + /// protocol. + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, atKeyPath keyPath: String, context: MapContext? = nil) throws -> [T] { + guard let array = (try mapJSON() as? NSDictionary)?.value(forKeyPath: keyPath) as? [[String: Any]] else { + throw MoyaError.jsonMapping(self) + } + return try Mapper(context: context).mapArray(JSONArray: array) + } + +} diff --git a/QuickLocation/Core/Extension/ScaleType.swift b/QuickLocation/Core/Extension/ScaleType.swift new file mode 100644 index 00000000..5409835f --- /dev/null +++ b/QuickLocation/Core/Extension/ScaleType.swift @@ -0,0 +1,33 @@ +// +// Float+Extension.swift +// dinoGo +// +// Created by osell on 2022/11/3. +// Copyright © 2022 dino. All rights reserved. +// + +import Foundation + + +public protocol ScaleType { + var scale: CGFloat { get } +} + +extension CGFloat: ScaleType { + public var scale: CGFloat { + (self / 375.0) * kScreenWidth + } +} + +extension Float: ScaleType { + public var scale: CGFloat { + CGFloat(self / 375.0) * kScreenWidth + } +} + +extension Int: ScaleType { + public var scale: CGFloat { + CGFloat(self) / 375.0 * kScreenWidth + } +} + diff --git a/QuickLocation/Core/Extension/String+Extension.swift b/QuickLocation/Core/Extension/String+Extension.swift new file mode 100644 index 00000000..4c49b50a --- /dev/null +++ b/QuickLocation/Core/Extension/String+Extension.swift @@ -0,0 +1,486 @@ +// +// String+public extension.swift +// SwiftBasics +// +// Created by 侯伟 on 17/1/11. +// Copyright © 2017年 侯伟. All rights reserved. +// + +import Foundation +import SwiftyJSON +import CommonCrypto +import URLNavigator + + +public extension String { + var completePicUrl: String { + if !self.hasPrefix("http") { + if self.hasPrefix("//") { + return "http:" + self + } else { + return "http://fec-img.gan-hai.com" + self + } + } else { + return self + } + } + var length: Int { return self.count } +} + +public extension JSON { + /// JSON to String + var jsonString: String { return rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions()) ?? "" } +} + +// MARK: URL encode/decode + +public extension String { + /// URL编码 + var urlEncoded: String { + return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) ?? self + } + + var urlEncodingWithQueryAllowedCharacters: String { + return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? self + } + + /// URL解码 + var urlDecoded: String { + return self.removingPercentEncoding ?? self + } +} + +// MARK: md5 +public extension String { + var MD5String: String { + + let cStrl = cString(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)); + + let buffer = UnsafeMutablePointer.allocate(capacity: 16); + + CC_MD5(cStrl, CC_LONG(strlen(cStrl!)), buffer); + + var md5String = ""; + + for idx in 0...15 { + + let obcStrl = String.init(format: "%02x", buffer[idx]); + + md5String.append(obcStrl); + + } + + free(buffer); + + return md5String; + + } +} +// MARK: Base64 + +public extension String { + /// Base64编码 + var base64Encoded: String { + return data.base64EncodedString(options: []) + } + + /// Base64解码 + var base64Decoded: String { + return Data(base64Encoded: self, options: [])?.string ?? "" + } +} + + +public extension String { + var md5: String { + let data = self.data + var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) + CC_MD5((data as NSData).bytes, CC_LONG(data.count), &digest) + let hexBytes = digest.map { String(format: "%02hhx", $0) } + return hexBytes.joined(separator: "") + } + + var sha1: String { + let data = self.data + var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) + CC_SHA1((data as NSData).bytes, CC_LONG(data.count), &digest) + let hexBytes = digest.map { String(format: "%02hhx", $0) } + return hexBytes.joined(separator: "") + } +} +// MARK: Get the size of the text + +public extension String { + /// 计算制定字体大小的文字显示尺寸(系统默认字体) + func size(fontSize: CGFloat, width: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize { + return size(font: UIFont.systemFont(ofSize: fontSize), width: width) + } + + /// 计算制定字体的文字显示尺寸 + func size(font: UIFont, width: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize { + let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineBreakMode = .byWordWrapping + let attributes = [ + NSAttributedString.Key.font: font, + NSAttributedString.Key.paragraphStyle: paragraphStyle.copy() + ] + + return (self as NSString).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size + } + + /// 获取文字几行的高度 + /// - Parameter count: 几行 + /// - Returns: 高度 + func lineHeight(_ count: Int = 1, + font: UIFont, + width: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat { + size(font: font, width: width).height * CGFloat(count) + } +} + +// MARK: Substring +public extension String { + func substring(_ fromIndex: Int, _ toIndex: Int = Int.max) -> String? { + let len = self.length + var start: Int + var end: Int + if fromIndex < 0 { + start = 0 + end = len + fromIndex + } else { + start = fromIndex + if toIndex < 0 { + end = len + toIndex + } else { + end = min(toIndex, len) + } + } + + if start > end { + return nil + } + + return self[start..) -> String? { + let len = self.length + if range.lowerBound >= len || range.upperBound < 0 { + return nil + } + + let startIndex = self.index(self.startIndex, offsetBy: max(0, range.lowerBound)) + let endIndex = self.index(self.startIndex, offsetBy: min(len, range.upperBound)) + + return String(self[startIndex.. Character? { + if index < 0 || index >= self.length { + return nil + } + return self[self.index(self.startIndex, offsetBy: index)] + } +} + +// MARK: Trim + +public extension String { + /// 删除前后空白符(包含空格、Tab、回车、换行符) + var trimmed: String { + return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + } +} + +// MARK: Localized String + +public extension String { + var localizedString: String { + return NSLocalizedString(self, comment: "") + } +} + +// MARK: - NSData + +public extension String { + /// 返回UTF8字符集的NSData对象 + var data: Data { + return self.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } +} + +public extension Data { + /// 返回UTF8字符串 + var string: String { + return String(data: self, encoding: String.Encoding.utf8) ?? "" + } +} + +// MARK: - Int + +public extension String { + var int: Int32 { return (self as NSString).intValue } + var integer: Int { return (self as NSString).integerValue } +} + +public extension Int { + var string: String { return String(self) } +} + +// MARK: - Float + +public extension String { + var float: Float { return (self as NSString).floatValue } +} + +public extension Float { + var string: String { return String(self) } +} + +// MARK: - Double + +public extension String { + var double: Double { return (self as NSString).doubleValue } +} + +public extension Double { + var string: String { return String(self) } +} + +// MARK: - Bool + +public extension String { + var bool: Bool { return (self as NSString).boolValue } +} + +public extension Bool { + var string: String { return self ? "true" : "false" } +} + +public extension String { + // 对象方法 + func getFileSize() -> UInt64 { + var size: UInt64 = 0 + let fileManager = FileManager.default + var isDir: ObjCBool = false + let isExists = fileManager.fileExists(atPath: self, isDirectory: &isDir) + // 判断文件存在 + if isExists { + // 是否为文件夹 + if isDir.boolValue { + // 迭代器 存放文件夹下的所有文件名 + let enumerator = fileManager.enumerator(atPath: self) + for subPath in enumerator! { + // 获得全路径 + let fullPath = self.appending("/\(subPath)") + do { + let attr = try fileManager.attributesOfItem(atPath: fullPath) + size += attr[FileAttributeKey.size] as! UInt64 + } catch { + print("error :\(error)") + } + } + } else { // 单文件 + do { + let attr = try fileManager.attributesOfItem(atPath: self) + size += attr[FileAttributeKey.size] as! UInt64 + + } catch { + print("error :\(error)") + } + } + } + return size + } +} + +// MARK: - 文字颜色 +public extension String { + func changeTextColor(color: UIColor, font: UIFont, text: String) -> NSMutableAttributedString { + let nsString = NSString(string: self) + let attributeString = NSMutableAttributedString(string: self) + let arrRange = rangeOfString(string: nsString, andInString: text) + for range in arrRange { + attributeString.addAttributes([NSAttributedString.Key.font: font], range: range) + attributeString.addAttributes([NSAttributedString.Key.foregroundColor: color], range: range) + } + + return attributeString + } + + func changeTextColor(color: UIColor, font: UIFont, firstText: String, secondText: String) -> NSMutableAttributedString { + let nsString = NSString(string: self) + let attributeString = NSMutableAttributedString(string: self) + let firstArrRange = rangeOfString(string: nsString, andInString: firstText) + for range in firstArrRange { + attributeString.addAttributes([NSAttributedString.Key.font: font], range: range) + attributeString.addAttributes([NSAttributedString.Key.foregroundColor: color], range: range) + } + let secondArrRange = rangeOfString(string: nsString, andInString: secondText) + for range in secondArrRange { + attributeString.addAttributes([NSAttributedString.Key.font: font], range: range) + attributeString.addAttributes([NSAttributedString.Key.foregroundColor: color], range: range) + } + + return attributeString + } + + /// 获取字符出现的位置信息(支持多次位置获取) + /// - Parameter string: 原始文本 + /// - Parameter inString: 需要查找的字符 + private func rangeOfString(string:NSString, + andInString inString:String) -> [NSRange] { + + var arrRange = [NSRange]() + var _fullText = string + var rang:NSRange = _fullText.range(of: inString) + + while rang.location != NSNotFound { + var location:Int = 0 + if arrRange.count > 0 { + if arrRange.last!.location + arrRange.last!.length < string.length { + location = arrRange.last!.location + arrRange.last!.length + } + } + + _fullText = NSString.init(string: _fullText.substring(from: rang.location + rang.length)) + + if arrRange.count > 0 { + rang.location += location + } + arrRange.append(rang) + + rang = _fullText.range(of: inString) + } + + return arrRange + } +} + +public extension String { + + /// 从URL字符串解析查询参数 + var urlQueryParameters: [String: String] { + guard let url = URL(string: self) else { return [:] } + return url.queryParameters + } + + /// 从String中截取出参数 + var urlParameters: [String: AnyObject]? { + // 判断是否有参数 + let text = self as NSString + let range = text.range(of: "?") + var params = [String: AnyObject]() + // 截取参数 + let paramsString = text.substring(with: range) + // 判断参数是单个参数还是多个参数 + if paramsString.contains("&") { + // 多个参数,分割参数 + let urlComponents = paramsString.components(separatedBy: "&") + // 遍历参数 + for keyValuePair in urlComponents { + // 生成Key/Value + let pairComponents = keyValuePair.components(separatedBy: "=") + let key = pairComponents.first?.removingPercentEncoding + let value = pairComponents.last?.removingPercentEncoding + // 判断参数是否是数组 + if let key = key, let value = value { + params[key] = value as AnyObject + // 已存在的值,生成数组 +// if let existValue = params[key] { +// if var existValue = existValue as? [AnyObject] { +// existValue.append(value) +// } else { +// params[key] = [existValue, value] +// } +// } else { +// params[key] = value as AnyObject +// } + } + } + } else { + // 单个参数 + let pairComponents = paramsString.components(separatedBy: "=") + // 判断是否有值 + if pairComponents.count == 1 { + return nil + } + let key = pairComponents.first?.removingPercentEncoding + let value = pairComponents.last?.removingPercentEncoding + if let key = key, let value = value { + params[key] = value as AnyObject + } + } + return params + } +} + +public extension String { + func custemReplaceString(of targetStr:String, + with replaceStr:String, + replaceColor: UIColor) -> NSMutableAttributedString { + let labelString = self.replacingOccurrences(of: targetStr, with: replaceStr) + let nsString = labelString as NSString + let range = nsString.range(of: replaceStr) + let mutableStr = NSMutableAttributedString(string: labelString) + mutableStr.setAttributes([NSAttributedString.Key.foregroundColor: replaceColor], range: range) + return mutableStr + } + +} + +public extension String { + /// 手机号格式化去0 + var phoneFromatter: String { + if let phone = Int64(self) { + return String(phone) + } + return self + } +} + +// MARK: - 转换为NSNumber +public extension String { + + var number: NSNumber? { + let boolNumbers = ["true": true, "false": false, "yes": true, "no": false] + let nilNumbers = ["nil", "null", "(null)", ""] + let lowerStr = self.lowercased() + if let value = boolNumbers[lowerStr] { return NSNumber(value: value) } + if nilNumbers.contains(lowerStr) { return nil } + + guard let cstring = self.cString(using: .utf8) else { return nil } + if self.rangeOfCharacter(from: CharacterSet(charactersIn: ".")) != nil { + let cnumber = atof(cstring) + if cnumber.isNaN || cnumber.isInfinite { return nil } + return NSNumber(value: cnumber) + } else { + return NSNumber(value: atoll(cstring)) + } + } +} + +// MARK: - 正则 +public extension String { + /// 检测Email 邮箱格式是否有效 + static func checkEmailAddressIsValid(address: String?) -> Bool { + guard address != nil else { + return false + } + let regular = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" + let regularEmail = NSPredicate(format: "SELF MATCHES %@", regular) + return regularEmail.evaluate(with: address) + } +} + +// MARK: - 手机号中间用 **** 替换 +extension String { + /// 手机号中间隐藏 + func phoneFormat() -> String { + guard self.length > 6 else { return self } + let preStr = self.substring(0, 3) + let suffixStr = self.substring(self.length - 4, self.length) + return (preStr ?? "") + "****" + (suffixStr ?? "") + } +} diff --git a/QuickLocation/Core/Extension/UIApplicationExtension.swift b/QuickLocation/Core/Extension/UIApplicationExtension.swift new file mode 100644 index 00000000..10e8ec9f --- /dev/null +++ b/QuickLocation/Core/Extension/UIApplicationExtension.swift @@ -0,0 +1,66 @@ +// +// UIApplicationExtension.swift +// OnlineMassage +// +// Created by Pluto on 2023/4/9. +// + +import UIKit + +public extension UIApplication { + + static var keyWindow: UIWindow? { + shared.windows.filter { $0.isKeyWindow }.first + } + + static func delegate() -> T? { + shared.delegate as? T + } + + static var rootViewController: UIViewController? { + getRootViewController(keyWindow?.rootViewController) + } + + static func getRootViewController(_ inViewController: UIViewController?) -> UIViewController? { + + guard let rootVc = inViewController else { return nil } + + if rootVc.isKind(of: UINavigationController.self) { + return getRootViewController((rootVc as? UINavigationController)?.visibleViewController) + } else if rootVc.isKind(of: UITabBarController.self) { + return getRootViewController((rootVc as? UITabBarController)?.selectedViewController) + } else { + return rootVc + } + } + + static func open(_ url: String, + options: [UIApplication.OpenExternalURLOptionsKey: Any] = [:], + completionHandler completion: ((Bool) -> Void)? = nil) { + + guard let url = URL(string: url) + else { + return + } + + if UIApplication.shared.canOpenURL(url) { + UIApplication.shared.open(url, options: options, completionHandler: completion) + } + } + + static var bundleId: String? { + Bundle.main.bundleIdentifier + } + + static var displayName: String? { + Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String + } + + static var buildNumber: String? { + Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String + } + + static var version: String? { + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String + } +} diff --git a/QuickLocation/Core/Extension/UIButton+Extension.swift b/QuickLocation/Core/Extension/UIButton+Extension.swift new file mode 100644 index 00000000..47c9bd01 --- /dev/null +++ b/QuickLocation/Core/Extension/UIButton+Extension.swift @@ -0,0 +1,88 @@ +// +// UIButton+Extension.swift +// dinoGo +// +// Created by osell on 2022/12/7. +// Copyright © 2022 dino. All rights reserved. +// + +import Foundation + +extension UIButton { + + /// 设置图片的居中边位置,需要在setImage和setTitle之后调用才生效,且button大小大于图片+文字+间距 + /// - Parameters: + /// - edge: 仅有image时相对于button,都有时上左下相对于button,右相对于title, 仅有title时相对于button,都有时上右下相对于button,左相对于image + /// - spacing: 距离 + public func setImageEdge(_ edge: UIRectEdge, spacing: CGFloat) { + let imageSize = imageView?.image?.size ?? .zero + let labelSize = titleLabel?.intrinsicContentSize ?? .zero + + switch edge { + case .left: + imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2.0, bottom: 0, right: spacing / 2.0) + titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2.0, bottom: 0, right: -spacing / 2.0) + case .right: + imageEdgeInsets = UIEdgeInsets(top: 0, left: labelSize.width + spacing / 2.0, bottom: 0, right: -labelSize.width - spacing / 2.0) + titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width - spacing / 2.0, bottom: 0, right: imageSize.width + spacing / 2.0) + case .top: + imageEdgeInsets = UIEdgeInsets(top: -labelSize.height - spacing / 2.0, left: 0, bottom: spacing / 2.0, right: -labelSize.width) + titleEdgeInsets = UIEdgeInsets(top: spacing / 2.0, left: -imageSize.width, bottom: -imageSize.height - spacing / 2.0, right: 0) + case .bottom: + imageEdgeInsets = UIEdgeInsets(top: spacing / 2.0, left: 0, bottom: -labelSize.height - spacing / 2.0, right: -labelSize.width) + titleEdgeInsets = UIEdgeInsets(top: -imageSize.height - spacing / 2.0, left: -imageSize.width, bottom: spacing / 2.0, right: 0) + default: + break + } + } + + /// 设置按钮背景颜色 + /// - Parameters: + /// - backgroundColor: 颜色 + /// - state: 状态 + public func setBackgroundColor(_ backgroundColor: UIColor, for state: UIControl.State) { + var image: UIImage? + let rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1)) + UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) + if let context = UIGraphicsGetCurrentContext() { + context.setFillColor(backgroundColor.cgColor) + context.fill(rect) + image = UIGraphicsGetImageFromCurrentImageContext() + } + UIGraphicsEndImageContext() + setBackgroundImage(image, for: state) + } +} + +// MARK: - 扩大按钮点击区域 +extension UIButton { + /// 设置此属性即可扩大响应范围, 分别对应上左下右 + /// 优势:与Auto-Layout无缝配合 + /// 劣势:View Debugger 查看不到增加的响应区域有多大, + private static var ExtendEdgeInsetsKey = "ExtendEdgeInsetsKey" + + var extendEdgeInsets: UIEdgeInsets { + get { + return objc_getAssociatedObject(self, &UIButton.ExtendEdgeInsetsKey) as? UIEdgeInsets ?? UIEdgeInsets.zero + } + set { + objc_setAssociatedObject(self, &UIButton.ExtendEdgeInsetsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + if UIEdgeInsetsEqualToEdgeInsets(extendEdgeInsets, .zero) || !self.isEnabled || self.isHidden || self.alpha < 0.01 { + return super.point(inside: point, with: event) + } + let newRect = extendRect(bounds, extendEdgeInsets) + return newRect.contains(point) + } + + private func extendRect(_ rect: CGRect, _ edgeInsets: UIEdgeInsets) -> CGRect { + let x = rect.minX - edgeInsets.left + let y = rect.minY - edgeInsets.top + let w = rect.width + edgeInsets.left + edgeInsets.right + let h = rect.height + edgeInsets.top + edgeInsets.bottom + return CGRect(x: x, y: y, width: w, height: h) + } +} diff --git a/QuickLocation/Core/Extension/UIColor+Extension.swift b/QuickLocation/Core/Extension/UIColor+Extension.swift new file mode 100644 index 00000000..aafb44b5 --- /dev/null +++ b/QuickLocation/Core/Extension/UIColor+Extension.swift @@ -0,0 +1,82 @@ +// +// File.swift +// DLSDK-DLSDK +// +// Created by osell on 2023/2/1. +// + +import Foundation +import UIKit + +@objc +public extension UIColor { + + /// 16进制字符串初始化UIColor + /// - Parameters: + /// - hexString: 16进制字符串 + /// - alpha: 透明度, 0~1.0 + convenience init(hexStr: String, alpha: CGFloat = 1.0) { + let hexString = hexStr.trimmingCharacters(in: .whitespacesAndNewlines) + let scanner = Scanner(string: hexString) + + if hexString.hasPrefix("#") { + scanner.scanLocation = 1 + } + + var color: UInt32 = 0 + scanner.scanHexInt32(&color) + + let mask = 0x000000FF + let r = Int(color >> 16) & mask + let g = Int(color >> 8) & mask + let b = Int(color) & mask + + let red = CGFloat(r) / 255.0 + let green = CGFloat(g) / 255.0 + let blue = CGFloat(b) / 255.0 + + self.init(red: red, green: green, blue: blue, alpha: alpha) + } + + /// 16进制初始化UIColor + /// - Parameters: + /// - hex: 16进制颜色值 + /// - alpha: 透明度, 0~1.0 + convenience init(hex: Int, alpha: CGFloat = 1.0) { + let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 + let green = CGFloat((hex & 0xFF00) >> 8) / 255.0 + let blue = CGFloat(hex & 0xFF) / 255.0 + self.init(red: red, green: green, blue: blue, alpha: alpha) + } + + /// 16进制颜色 + /// - Parameters: + /// - hex: 16进制颜色值 + /// - alpha: 透明度,0~1.0 + /// - Returns: 颜色 + static func colorHex(_ hex: Int, alpha: CGFloat = 1.0) -> UIColor { + let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 + let green = CGFloat((hex & 0xFF00) >> 8) / 255.0 + let blue = CGFloat(hex & 0xFF) / 255.0 + return UIColor(red: red, green: green, blue: blue, alpha: alpha) + } + + /// 获取颜色的16进制字符串 + /// - Parameter includeAlpha: 是否包含透明度 + /// - Returns: 颜色的16进制字符串 + func hexString(_ includeAlpha: Bool = true) -> String { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + self.getRed(&r, green: &g, blue: &b, alpha: &a) + + if (includeAlpha) { + return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) + } else { + return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) + } + } + +} + diff --git a/QuickLocation/Core/Extension/UIFont+Extension.swift b/QuickLocation/Core/Extension/UIFont+Extension.swift new file mode 100644 index 00000000..536ff3a3 --- /dev/null +++ b/QuickLocation/Core/Extension/UIFont+Extension.swift @@ -0,0 +1,106 @@ +// +// UIFont+Extension.swift +// DLSDK +// +// Created by osell on 2023/4/11. +// + +import UIKit + +// MARK: - 注册自定义字体数据 +public extension UIFont { + + /// 自定义字体样式 + /// - Parameters: + /// - style: 字体样式 + /// - size: 字体大小 + convenience init?(custom style: Style, size: CGFloat) { + var name = style.name + if UIFont.fontNames(forFamilyName: style.name).isEmpty, + let fontName = UIFont.loadFontName(style.fileName) { + name = fontName + } + self.init(name: name, size: size) + } + + /// 自定义字体样式 + /// - Parameters: + /// - style: 字体样式 + /// - size: 字体大小 + /// - Returns: UIFont + static func customFont(style: Style, size: CGFloat) -> UIFont? { + UIFont(custom: style, size: size) + } + + /// 加载本地自定义字体 + /// - Parameter name: 字体文件名称 + private static func loadFontName(_ fileName: String) -> String? { + // 字体文件资源路径 + guard let fontURL = Bundle.main.url(forResource: fileName, withExtension: nil), + let data = try? Data(contentsOf: fontURL), + let provider = CGDataProvider(data: data as CFData), + let font = CGFont(provider) else { return nil } + + // 注册字体 + CTFontManagerRegisterGraphicsFont(font, nil) + return String(font.fullName ?? "") + } +} + +// MARK: - Montserrat +//public extension UIFont { +// +// static func montserratLight(size: CGFloat) -> UIFont { +// Montserrat.light.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .light) +// } +// +// static func montserratRegular(size: CGFloat) -> UIFont { +// Montserrat.regular.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .regular) +// } +// +// static func montserratMedium(size: CGFloat) -> UIFont { +// Montserrat.medium.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .medium) +// } +// +// static func montserratSemiBold(size: CGFloat) -> UIFont { +// Montserrat.semiBold.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .semibold) +// } +// +// static func montserratBold(size: CGFloat) -> UIFont { +// Montserrat.bold.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .bold) +// } +//} + +// MARK: - DINPro +//public extension UIFont { +// +// static func dinProLight(size: CGFloat) -> UIFont { +// DINPro.light.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .light) +// } +// +// static func dinProRegular(size: CGFloat) -> UIFont { +// DINPro.regular.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .regular) +// } +// +// static func dinProMedium(size: CGFloat) -> UIFont { +// DINPro.medium.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .medium) +// } +// +// static func dinProBlack(size: CGFloat) -> UIFont { +// DINPro.black.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .black) +// } +// +// static func dinProBold(size: CGFloat) -> UIFont { +// DINPro.bold.font(ofSize: size) ?? UIFont.systemFont(ofSize: size, weight: .bold) +// } +//} + +// MARK: - FontPlugin +public protocol FontPlugin { + /// 字体名称 + var name: String { get } + /// 字体文件名 + var fileName: String { get } + /// 返回该类型大小字体 + func font(ofSize: CGFloat) -> UIFont? +} diff --git a/QuickLocation/Core/Extension/UIImage+Extension.swift b/QuickLocation/Core/Extension/UIImage+Extension.swift new file mode 100644 index 00000000..e910d83c --- /dev/null +++ b/QuickLocation/Core/Extension/UIImage+Extension.swift @@ -0,0 +1,462 @@ +// +// UIImage+Extension.swift +// GXM-CRM +// +// Created by XUXIAOTENG on 06/02/2018. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import Foundation +import UIKit + +public extension UIImage { + + func blend(with color: UIColor) -> UIImage? { + UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) + let context = UIGraphicsGetCurrentContext()! + let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) + // Unflip the image + context.translateBy(x: 0, y: size.height) + context.scaleBy(x: 1.0, y: -1.0) + + context.setBlendMode(.overlay) + context.draw(cgImage!, in: rect) + + context.setFillColor(color.cgColor) + context.fill(rect) + + let newImage = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + return newImage + } + + func blurImage(radius: CGFloat) -> UIImage { + let inputImage = CIImage(image: self)! + + let parameters: [String: Any] = [ + kCIInputRadiusKey: radius, + kCIInputImageKey: inputImage + ] + let filter = CIFilter(name: "CIGaussianBlur", + parameters: parameters)! + + let cgimg = CIContext().createCGImage(filter.outputImage!, from: inputImage.extent) + return UIImage(cgImage: cgimg!) + } + + func saveToTemp(fileName: String) -> String? { + let dirURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let tempURL = dirURL.appendingPathComponent("GXM") + let fileURL = tempURL.appendingPathComponent(fileName).appendingPathExtension("jpg") + // 创建CRM目录 + if !FileManager.default.fileExists(atPath: tempURL.path) { + do { + try FileManager.default.createDirectory(at: tempURL, + withIntermediateDirectories: false, + attributes: nil) + } catch { + print("目录创建失败: \(error)") + ProgressHUD.showError(withStatus: error.localizedDescription) + } + } + if FileManager.default.fileExists(atPath: fileURL.path) { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + print("文件删除失败:\(error)") + ProgressHUD.showError(withStatus: error.localizedDescription) + } + } + if let data = self.jpegData(compressionQuality: 1.0) { + do { + try data.write(to: fileURL) + return fileURL.path + } catch { + print("文件保存失败:\(error)") + ProgressHUD.showError(withStatus: error.localizedDescription) + } + } + return nil + } + + // Thumbnail image + func thumbnail(size: CGFloat) -> UIImage { + let scale = UIScreen.main.scale + let length = size * scale + let thumbnail = resizeTo(CGSize(width: length, height: length), scale: false) ?? self + return thumbnail + } + + func resizeTo(_ size: CGSize) -> UIImage? { + guard let imgRef = cgImage else { return self } + let srcSize = CGSize(width: imgRef.width, height: imgRef.height) + var dstSize = size + + // Don't resize + guard !(srcSize.equalTo(dstSize)) else { return self } + + let scaleRatio: CGFloat = dstSize.width / srcSize.width + let orient = imageOrientation + var transform = CGAffineTransform.identity + + switch orient { + case .up: //EXIF = 1 + transform = CGAffineTransform.identity + + case .upMirrored: //EXIF = 2 + transform = CGAffineTransform(translationX: srcSize.width, y: 0) + transform = transform.scaledBy(x: -1.0, y: 1.0) + + case .down: //EXIF = 3 + transform = CGAffineTransform(translationX: srcSize.width, y: srcSize.height) + transform = transform.rotated(by: CGFloat.pi) + + case .downMirrored: //EXIF = 4 + transform = CGAffineTransform(translationX: 0, y: srcSize.height) + transform = transform.scaledBy(x: 1.0, y: -1.0) + + case .leftMirrored: //EXIF = 5 + dstSize = CGSize(width: dstSize.height, height: dstSize.width) + transform = CGAffineTransform(translationX: srcSize.height, y: srcSize.width) + transform = transform.scaledBy(x: -1.0, y: 1.0) + transform = transform.rotated(by: 3.0 * CGFloat.pi / 2.0) + + case .left: //EXIF = 6 + dstSize = CGSize(width: dstSize.height, height: dstSize.width) + transform = CGAffineTransform(translationX: 0.0, y: srcSize.width) + transform = transform.rotated(by: 3.0 * CGFloat.pi / 2.0) + + case .rightMirrored: //EXIF = 7 + dstSize = CGSize(width: dstSize.height, height: dstSize.width) + transform = CGAffineTransform(scaleX: -1.0, y: 1.0) + transform = transform.rotated(by: CGFloat.pi / 2.0) + + case .right: //EXIF = 8 + dstSize = CGSize(width: dstSize.height, height: dstSize.width) + transform = CGAffineTransform(translationX: srcSize.height, y: 0) + transform = transform.rotated(by: CGFloat.pi / 2.0) + @unknown default: + break + } + + // Draw the image on a new context, applying a transform matrix + UIGraphicsBeginImageContextWithOptions(dstSize, false, scale) + + guard let context = UIGraphicsGetCurrentContext() else { + return nil + } + + if orient == .right || orient == .left { + context.scaleBy(x: -scaleRatio, y: scaleRatio) + context.translateBy(x: -srcSize.height, y: 0) + } else { + context.scaleBy(x: scaleRatio, y: -scaleRatio) + context.translateBy(x: 0, y: -srcSize.height) + } + context.concatenate(transform) + + let rect = CGRect(x: 0, y: 0, width: srcSize.width, height: srcSize.height) + context.draw(imgRef, in: rect) + let resizedImage = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + + return resizedImage + } + + func resizeTo(_ size: CGSize, scale: Bool) -> UIImage? { + guard let imgRef = cgImage else { return self } + let srcSize = CGSize(width: imgRef.width, height: imgRef.height) + var boundingSize = size + + let orient = self.imageOrientation + switch orient { + case .left, + .right, + .leftMirrored, + .rightMirrored: + boundingSize = CGSize(width: boundingSize.height, height: boundingSize.width) + default: + // NOP + break + } + + // Compute the target CGRect + var dstSize: CGSize + + if !scale && srcSize.width < boundingSize.width && srcSize.height < boundingSize.height { + // no resize (draw the image anyway to take image orientation into account) + dstSize = srcSize + } else { + let wRatio = boundingSize.width / srcSize.width + let hRatio = boundingSize.height / srcSize.height + + if wRatio < hRatio { + dstSize = CGSize(width: boundingSize.width, height: CGFloat(floorf(Float(srcSize.height * wRatio)))) + } else { + dstSize = CGSize(width: CGFloat(floorf(Float(srcSize.width * hRatio))), height: boundingSize.height) + } + } + + return resizeTo(dstSize) + } + +} + +public extension UIImage { + + func scaledWidth(for height: CGFloat) -> CGFloat { + return height * size.width / size.height + } + + func scaledHeight(for width: CGFloat) -> CGFloat { + return width * size.height / size.width + } +} + +public extension UIImage { + /// 更改图片颜色/大小 + /// - Parameters: + /// - tintColor: 颜色 + /// - scaleSize: 缩放size + /// - blendMode: 默认destinationIn + /// - Returns: 图片 + func image(tintColor: UIColor, + scaleSize : CGSize, + blendMode: CGBlendMode = .destinationIn) -> UIImage? { + let tempSize = scaleSize == .zero ? size : scaleSize + UIGraphicsBeginImageContextWithOptions(tempSize, false, 0.0) + // 更改图片大小 + let bounds = CGRect(x: 0, y: 0, width: tempSize.width, height: tempSize.height) + // 更改图片颜色 + tintColor.setFill() + UIRectFill(bounds) + draw(in: bounds, blendMode: blendMode, alpha: 1.0) + guard let tintImage = UIGraphicsGetImageFromCurrentImageContext() else { + return self + } + UIGraphicsEndImageContext() + return tintImage + } + + /// 更改图片颜色 + /// - Parameters: + /// - tintColor: 颜色 + /// - blendMode: 默认destinationIn + /// - Returns: 图片 + func image(tintColor: UIColor, + blendMode: CGBlendMode = .destinationIn) -> UIImage? { + UIGraphicsBeginImageContextWithOptions(size, false, 0.0) + let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height) + // 更改图片颜色 + tintColor.setFill() + UIRectFill(bounds) + draw(in: bounds, blendMode: blendMode, alpha: 1.0) + guard let tintImage = UIGraphicsGetImageFromCurrentImageContext() else { + return self + } + UIGraphicsEndImageContext() + return tintImage + } + + /// 更改图片大小 + /// - Parameters: + /// - scaleSize: 缩放size + /// - blendMode: 默认destinationIn + /// - Returns: 图片 + func image(scaleSize : CGSize, + blendMode: CGBlendMode = .destinationIn) -> UIImage? { + let tempSize = scaleSize == .zero ? size : scaleSize + UIGraphicsBeginImageContextWithOptions(tempSize, false, 0.0) + // 更改图片大小 + let bounds = CGRect(x: 0, y: 0, width: tempSize.width, height: tempSize.height) + UIRectFill(bounds) + draw(in: bounds, blendMode: blendMode, alpha: 1.0) + guard let tintImage = UIGraphicsGetImageFromCurrentImageContext() else { + return self + } + UIGraphicsEndImageContext() + return tintImage + } + + /// 生成颜色图片 + /// - Parameter color: 颜色 + /// - Returns: UIImage + static func colorImage(with color: UIColor) -> UIImage? { + var image: UIImage? + let rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1)) + UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) + if let context = UIGraphicsGetCurrentContext() { + context.setFillColor(color.cgColor) + context.fill(rect) + image = UIGraphicsGetImageFromCurrentImageContext() + } + UIGraphicsEndImageContext() + return image + } +} + +// MARK: - 旋转图片 +extension UIImage { + /// 图片镜像处理 + public var adaptiveImage: UIImage? { + guard let cgImage = cgImage else { return nil } + let flippedImage = UIImage(cgImage: cgImage, scale: scale, orientation: UIView.appearance().semanticContentAttribute == .forceRightToLeft ? .upMirrored : .up) + return flippedImage + } +} + +// MARK: - 压缩图片 +extension UIImage { + public func compressImage(maxSize: CGFloat) -> Data? { + var imageData = self.jpegData(compressionQuality: 1.0) + if imageData?.count ?? 0 > Int(maxSize) { + var compressionQuality = 1.0 + let sizeRatio = self.size.width / self.size.height + + var resizedImage = resizeImage(image: self, targetSize: CGSize(width: 360, height: 360 / sizeRatio)) + imageData = resizedImage?.jpegData(compressionQuality: compressionQuality) + + while imageData?.count ?? 0 > Int(maxSize) { + compressionQuality -= 0.1 +// resizedImage = resizeImage(image: resizedImage!, targetSize: CGSize(width: resizedImage!.size.width, +// height: resizedImage!.size.height)) + imageData = resizedImage?.jpegData(compressionQuality: compressionQuality) + } + } + return imageData + } + + private func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? { + let size = image.size + +// let widthRatio = targetSize.width / size.width +// let heightRatio = targetSize.height / size.height +// +// let newSize: CGSize +// if widthRatio > heightRatio { +// newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) +// } else { +// newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) +// } + + UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0) + image.draw(in: CGRect(origin: CGPoint.zero, size: targetSize)) + let newImage = UIGraphicsGetImageFromCurrentImageContext() + UIGraphicsEndImageContext() + + return newImage + } +} + +// 修复图片旋转 +extension UIImage { + public func fixOrientation() -> UIImage { + if self.imageOrientation == .up { + return self + } + + var transform = CGAffineTransform.identity + + switch self.imageOrientation { + case .down, .downMirrored: + transform = transform.translatedBy(x: self.size.width, y: self.size.height) + transform = transform.rotated(by: .pi) + break + + case .left, .leftMirrored: + transform = transform.translatedBy(x: self.size.width, y: 0) + transform = transform.rotated(by: .pi / 2) + break + + case .right, .rightMirrored: + transform = transform.translatedBy(x: 0, y: self.size.height) + transform = transform.rotated(by: -.pi / 2) + break + + default: + break + } + + switch self.imageOrientation { + case .upMirrored, .downMirrored: + transform = transform.translatedBy(x: self.size.width, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + break + + case .leftMirrored, .rightMirrored: + transform = transform.translatedBy(x: self.size.height, y: 0); + transform = transform.scaledBy(x: -1, y: 1) + break + + default: + break + } + + let ctx = CGContext(data: nil, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0, space: self.cgImage!.colorSpace!, bitmapInfo: self.cgImage!.bitmapInfo.rawValue) + ctx?.concatenate(transform) + + switch self.imageOrientation { + case .left, .leftMirrored, .right, .rightMirrored: + ctx?.draw(self.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(size.height), height: CGFloat(size.width))) + break + + default: + ctx?.draw(self.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(size.width), height: CGFloat(size.height))) + break + } + + let cgimg: CGImage = (ctx?.makeImage())! + let img = UIImage(cgImage: cgimg) + + return img + } +} + +// UIImage扩展:支持从Data创建GIF动画 +extension UIImage { + class func gifImageWithData(_ data: Data) -> UIImage? { + // 创建图片源 + guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { + return nil + } + + let count = CGImageSourceGetCount(source) + var images = [UIImage]() + var duration: TimeInterval = 0 + + // 遍历所有帧 + for i in 0.. TimeInterval { + let defaultDuration = 0.1 + guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [AnyHashable: Any] else { + return defaultDuration + } + + guard let gifProperties = properties[kCGImagePropertyGIFDictionary as String] as? [AnyHashable: Any] else { + return defaultDuration + } + + // 处理GIF的延迟时间 + if let delayTime = gifProperties[kCGImagePropertyGIFDelayTime as String] as? TimeInterval { + return delayTime > 0 ? delayTime : defaultDuration + } + + return defaultDuration + } +} diff --git a/QuickLocation/Core/Extension/UIImage+Resource.swift b/QuickLocation/Core/Extension/UIImage+Resource.swift new file mode 100644 index 00000000..d6a99b59 --- /dev/null +++ b/QuickLocation/Core/Extension/UIImage+Resource.swift @@ -0,0 +1,20 @@ +// +// UIImage+Resource.swift +// QuickLocation +// + +import UIKit + +extension UIImage { + + /// 从 Resources 目录加载切图,兼容 Assets.xcassets + static func resource(_ name: String) -> UIImage? { + if let assetImg = UIImage(named: name) { + return assetImg + } + guard let path = Bundle.main.path(forResource: name, ofType: nil) else { + return nil + } + return UIImage(contentsOfFile: path) + } +} diff --git a/QuickLocation/Core/Extension/UILabel+Extension.swift b/QuickLocation/Core/Extension/UILabel+Extension.swift new file mode 100644 index 00000000..61cf2187 --- /dev/null +++ b/QuickLocation/Core/Extension/UILabel+Extension.swift @@ -0,0 +1,104 @@ +// +// UILabel+Extension.swift +// HealthyZG +// +// Created by 林 on 2020/7/21. +// Copyright © 2020 Lin. All rights reserved. +// + +import Foundation +import UIKit + +extension UILabel { + /// 删除线 + public func setupStrikethroughStyle(_ withText: String="") { + guard let text = self.text else { return } + let attributeText = NSMutableAttributedString(string: text) + let nsString = NSString(string: text) + var range = nsString.range(of: text) + if !withText.isEmpty, text.contains(withText) { + range = nsString.range(of: withText) + } + attributeText.addAttribute(.strikethroughStyle, value: 1, range: range) + self.attributedText = attributeText + } + + /// 设置¥或单位的字体样式 + public func setupMoneyStyle(moneyValue: String, symbol: String, unit: String, fontStyle: UIFont) { + let nsString = NSString(string: moneyValue) + let symbolRange = nsString.range(of: symbol) + let unitRange = nsString.range(of: unit) + let attString = NSMutableAttributedString(string: moneyValue) + attString.addAttributes([NSAttributedString.Key.font: fontStyle], range: symbolRange) + attString.addAttributes([NSAttributedString.Key.font: fontStyle], range: unitRange) + self.attributedText = attString + } + + /// 设置符号(比如¥)字体样式 + public func setupMoneyStyle(symbol: String, fontStyle: UIFont) { + let text = self.text ?? "" + let nsString = NSString(string: text) + let symbolRange = nsString.range(of: symbol) + let attString = NSMutableAttributedString(string: text) + attString.addAttributes([NSAttributedString.Key.font: fontStyle], range: symbolRange) + self.attributedText = attString + } + + /// 设置字体样式 + public func setupTextStyle(text: String, font: UIFont, color: UIColor) { + if let labelText = self.text { + let nsString = NSString(string: labelText) + let textRange = nsString.range(of: text) + let attString = NSMutableAttributedString(string: labelText) + attString.addAttributes([NSAttributedString.Key.font: font, + NSAttributedString.Key.foregroundColor: color], + range: textRange) + self.attributedText = attString + } + } + + public func setupTextStyle(text: String, color: UIColor) { + if let labelText = self.text { + let nsString = NSString(string: labelText) + let textRange = nsString.range(of: text) + let attString = NSMutableAttributedString(string: labelText) + attString.addAttributes([NSAttributedString.Key.foregroundColor: color], + range: textRange) + self.attributedText = attString + } + } +} + +extension UILabel { + /** + 设置Label字体、颜色 + */ + public func setupStyle(font: UIFont, textColor: UIColor) { + self.font = font + self.textColor = textColor + } +} + +extension UILabel { + func setLineSpacing(lineSpacing: CGFloat = 0.0) { + guard let labelText = self.text else { return } + + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = lineSpacing + + let attributedString: NSMutableAttributedString + if let labelAttributedText = self.attributedText { + attributedString = NSMutableAttributedString(attributedString: labelAttributedText) + } else { + attributedString = NSMutableAttributedString(string: labelText) + } + + attributedString.addAttribute( + .paragraphStyle, + value: paragraphStyle, + range: NSMakeRange(0, attributedString.length) + ) + + self.attributedText = attributedString + } +} diff --git a/QuickLocation/Core/Extension/UINavigationController+FDFullscreenPopGesture.h b/QuickLocation/Core/Extension/UINavigationController+FDFullscreenPopGesture.h new file mode 100755 index 00000000..1be8de71 --- /dev/null +++ b/QuickLocation/Core/Extension/UINavigationController+FDFullscreenPopGesture.h @@ -0,0 +1,62 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 + +/// "UINavigation+FDFullscreenPopGesture" extends UINavigationController's swipe- +/// to-pop behavior in iOS 7+ by supporting fullscreen pan gesture. Instead of +/// screen edge, you can now swipe from any place on the screen and the onboard +/// interactive pop transition works seamlessly. +/// +/// Adding the implementation file of this category to your target will +/// automatically patch UINavigationController with this feature. +@interface UINavigationController (FDFullscreenPopGesture) + +/// The gesture recognizer that actually handles interactive pop. +@property (nonatomic, strong, readonly) UIPanGestureRecognizer *fd_fullscreenPopGestureRecognizer; + +/// A view controller is able to control navigation bar's appearance by itself, +/// rather than a global way, checking "fd_prefersNavigationBarHidden" property. +/// Default to YES, disable it if you don't want so. +@property (nonatomic, assign) BOOL fd_viewControllerBasedNavigationBarAppearanceEnabled; + +@end + +/// Allows any view controller to disable interactive pop gesture, which might +/// be necessary when the view controller itself handles pan gesture in some +/// cases. +@interface UIViewController (FDFullscreenPopGesture) + +/// Whether the interactive pop gesture is disabled when contained in a navigation +/// stack. +@property (nonatomic, assign) BOOL fd_interactivePopDisabled; + +/// Indicate this view controller prefers its navigation bar hidden or not, +/// checked when view controller based navigation bar's appearance is enabled. +/// Default to NO, bars are more likely to show. +@property (nonatomic, assign) BOOL fd_prefersNavigationBarHidden; + +/// Max allowed initial distance to left edge when you begin the interactive pop +/// gesture. 0 by default, which means it will ignore this limit. +@property (nonatomic, assign) CGFloat fd_interactivePopMaxAllowedInitialDistanceToLeftEdge; + +@end diff --git a/QuickLocation/Core/Extension/UINavigationController+FDFullscreenPopGesture.m b/QuickLocation/Core/Extension/UINavigationController+FDFullscreenPopGesture.m new file mode 100755 index 00000000..53a54bc8 --- /dev/null +++ b/QuickLocation/Core/Extension/UINavigationController+FDFullscreenPopGesture.m @@ -0,0 +1,292 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 "UINavigationController+FDFullscreenPopGesture.h" +#import + +@interface _FDFullscreenPopGestureRecognizerDelegate : NSObject + +@property (nonatomic, weak) UINavigationController *navigationController; + +@end + +@implementation _FDFullscreenPopGestureRecognizerDelegate + +- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer +{ + // Ignore when no view controller is pushed into the navigation stack. + if (self.navigationController.viewControllers.count <= 1) { + return NO; + } + + // Ignore when the active view controller doesn't allow interactive pop. + UIViewController *topViewController = self.navigationController.viewControllers.lastObject; + if (topViewController.fd_interactivePopDisabled) { + return NO; + } + + // Ignore when the beginning location is beyond max allowed initial distance to left edge. + CGPoint beginningLocation = [gestureRecognizer locationInView:gestureRecognizer.view]; + CGFloat maxAllowedInitialDistance = topViewController.fd_interactivePopMaxAllowedInitialDistanceToLeftEdge; + if (maxAllowedInitialDistance > 0 && beginningLocation.x > maxAllowedInitialDistance) { + return NO; + } + + // Ignore pan gesture when the navigation controller is currently in transition. + if ([[self.navigationController valueForKey:@"_isTransitioning"] boolValue]) { + return NO; + } + + // Prevent calling the handler when the gesture begins in an opposite direction. + CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view]; + BOOL isLeftToRight = [UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionLeftToRight; + CGFloat multiplier = isLeftToRight ? 1 : - 1; + if ((translation.x * multiplier) <= 0) { + return NO; + } + + return YES; +} + +@end + +typedef void (^_FDViewControllerWillAppearInjectBlock)(UIViewController *viewController, BOOL animated); + +@interface UIViewController (FDFullscreenPopGesturePrivate) + +@property (nonatomic, copy) _FDViewControllerWillAppearInjectBlock fd_willAppearInjectBlock; + +@end + +@implementation UIViewController (FDFullscreenPopGesturePrivate) + ++ (void)load +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Method viewWillAppear_originalMethod = class_getInstanceMethod(self, @selector(viewWillAppear:)); + Method viewWillAppear_swizzledMethod = class_getInstanceMethod(self, @selector(fd_viewWillAppear:)); + method_exchangeImplementations(viewWillAppear_originalMethod, viewWillAppear_swizzledMethod); + + Method viewWillDisappear_originalMethod = class_getInstanceMethod(self, @selector(viewWillDisappear:)); + Method viewWillDisappear_swizzledMethod = class_getInstanceMethod(self, @selector(fd_viewWillDisappear:)); + method_exchangeImplementations(viewWillDisappear_originalMethod, viewWillDisappear_swizzledMethod); + }); +} + +- (void)fd_viewWillAppear:(BOOL)animated +{ + // Forward to primary implementation. + [self fd_viewWillAppear:animated]; + + if (self.fd_willAppearInjectBlock) { + self.fd_willAppearInjectBlock(self, animated); + } +} + +- (void)fd_viewWillDisappear:(BOOL)animated +{ + // Forward to primary implementation. + [self fd_viewWillDisappear:animated]; + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + UIViewController *viewController = self.navigationController.viewControllers.lastObject; + if (viewController && !viewController.fd_prefersNavigationBarHidden) { + [self.navigationController setNavigationBarHidden:NO animated:NO]; + } + }); +} + +- (_FDViewControllerWillAppearInjectBlock)fd_willAppearInjectBlock +{ + return objc_getAssociatedObject(self, _cmd); +} + +- (void)setFd_willAppearInjectBlock:(_FDViewControllerWillAppearInjectBlock)block +{ + objc_setAssociatedObject(self, @selector(fd_willAppearInjectBlock), block, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +@end + +@implementation UINavigationController (FDFullscreenPopGesture) + ++ (void)load +{ + // Inject "-pushViewController:animated:" + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [self class]; + + SEL originalSelector = @selector(pushViewController:animated:); + SEL swizzledSelector = @selector(fd_pushViewController:animated:); + + Method originalMethod = class_getInstanceMethod(class, originalSelector); + Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); + + BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); + if (success) { + class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); + } else { + method_exchangeImplementations(originalMethod, swizzledMethod); + } + }); +} + +- (void)fd_pushViewController:(UIViewController *)viewController animated:(BOOL)animated +{ + if ([self isKindOfClass:NSClassFromString(@"MFMessageComposeViewController")]) { + [self fd_pushViewController:viewController animated:animated]; + return; + } + if (![self.interactivePopGestureRecognizer.view.gestureRecognizers containsObject:self.fd_fullscreenPopGestureRecognizer]) { + + // Add our own gesture recognizer to where the onboard screen edge pan gesture recognizer is attached to. + [self.interactivePopGestureRecognizer.view addGestureRecognizer:self.fd_fullscreenPopGestureRecognizer]; + + // Forward the gesture events to the private handler of the onboard gesture recognizer. + NSArray *internalTargets = [self.interactivePopGestureRecognizer valueForKey:@"targets"]; + id internalTarget = [internalTargets.firstObject valueForKey:@"target"]; + SEL internalAction = NSSelectorFromString(@"handleNavigationTransition:"); + self.fd_fullscreenPopGestureRecognizer.delegate = self.fd_popGestureRecognizerDelegate; + [self.fd_fullscreenPopGestureRecognizer addTarget:internalTarget action:internalAction]; + + // Disable the onboard gesture recognizer. + self.interactivePopGestureRecognizer.enabled = NO; + } + + // Handle perferred navigation bar appearance. + [self fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:viewController]; + + // Forward to primary implementation. + if (![self.viewControllers containsObject:viewController]) { + [self fd_pushViewController:viewController animated:animated]; + } +} + +- (void)fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:(UIViewController *)appearingViewController +{ + if (!self.fd_viewControllerBasedNavigationBarAppearanceEnabled) { + return; + } + + __weak typeof(self) weakSelf = self; + _FDViewControllerWillAppearInjectBlock block = ^(UIViewController *viewController, BOOL animated) { + __strong typeof(weakSelf) strongSelf = weakSelf; + if (strongSelf) { + [strongSelf setNavigationBarHidden:viewController.fd_prefersNavigationBarHidden animated:animated]; + } + }; + + // Setup will appear inject block to appearing view controller. + // Setup disappearing view controller as well, because not every view controller is added into + // stack by pushing, maybe by "-setViewControllers:". + appearingViewController.fd_willAppearInjectBlock = block; + UIViewController *disappearingViewController = self.viewControllers.lastObject; + if (disappearingViewController && !disappearingViewController.fd_willAppearInjectBlock) { + disappearingViewController.fd_willAppearInjectBlock = block; + } +} + +- (_FDFullscreenPopGestureRecognizerDelegate *)fd_popGestureRecognizerDelegate +{ + _FDFullscreenPopGestureRecognizerDelegate *delegate = objc_getAssociatedObject(self, _cmd); + + if (!delegate) { + delegate = [[_FDFullscreenPopGestureRecognizerDelegate alloc] init]; + delegate.navigationController = self; + + objc_setAssociatedObject(self, _cmd, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return delegate; +} + +- (UIPanGestureRecognizer *)fd_fullscreenPopGestureRecognizer +{ + UIPanGestureRecognizer *panGestureRecognizer = objc_getAssociatedObject(self, _cmd); + + if (!panGestureRecognizer) { + panGestureRecognizer = [[UIPanGestureRecognizer alloc] init]; + panGestureRecognizer.maximumNumberOfTouches = 1; + + objc_setAssociatedObject(self, _cmd, panGestureRecognizer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return panGestureRecognizer; +} + +- (BOOL)fd_viewControllerBasedNavigationBarAppearanceEnabled +{ + NSNumber *number = objc_getAssociatedObject(self, _cmd); + if (number) { + return number.boolValue; + } + self.fd_viewControllerBasedNavigationBarAppearanceEnabled = YES; + return YES; +} + +- (void)setFd_viewControllerBasedNavigationBarAppearanceEnabled:(BOOL)enabled +{ + SEL key = @selector(fd_viewControllerBasedNavigationBarAppearanceEnabled); + objc_setAssociatedObject(self, key, @(enabled), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +@implementation UIViewController (FDFullscreenPopGesture) + +- (BOOL)fd_interactivePopDisabled +{ + return [objc_getAssociatedObject(self, _cmd) boolValue]; +} + +- (void)setFd_interactivePopDisabled:(BOOL)disabled +{ + objc_setAssociatedObject(self, @selector(fd_interactivePopDisabled), @(disabled), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)fd_prefersNavigationBarHidden +{ + return [objc_getAssociatedObject(self, _cmd) boolValue]; +} + +- (void)setFd_prefersNavigationBarHidden:(BOOL)hidden +{ + objc_setAssociatedObject(self, @selector(fd_prefersNavigationBarHidden), @(hidden), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + + +- (CGFloat)fd_interactivePopMaxAllowedInitialDistanceToLeftEdge +{ +#if CGFLOAT_IS_DOUBLE + return [objc_getAssociatedObject(self, _cmd) doubleValue]; +#else + return [objc_getAssociatedObject(self, _cmd) floatValue]; +#endif +} + +- (void)setFd_interactivePopMaxAllowedInitialDistanceToLeftEdge:(CGFloat)distance +{ + SEL key = @selector(fd_interactivePopMaxAllowedInitialDistanceToLeftEdge); + objc_setAssociatedObject(self, key, @(MAX(0, distance)), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/QuickLocation/Core/Extension/UITableView+Extension.swift b/QuickLocation/Core/Extension/UITableView+Extension.swift new file mode 100644 index 00000000..bfed2114 --- /dev/null +++ b/QuickLocation/Core/Extension/UITableView+Extension.swift @@ -0,0 +1,43 @@ +// +// UITableView+Extesion.swift +// DLSDK +// +// Created by osell on 2023/5/31. +// + +import UIKit + +public extension UITableView { + + func restGroupStyle() { + tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFLOAT_MIN)) + tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFLOAT_MIN)) + estimatedSectionHeaderHeight = 0 + estimatedSectionFooterHeight = 0 + if #available(iOS 15.0, *) { + sectionHeaderTopPadding = 0 + } + } + +} + +extension UITableView { + func scrollToTop(animated: Bool = false) { + let topOffset: CGPoint + + if self.style == .grouped { + topOffset = CGPoint(x: 0, y: -self.safeAreaInsets.top) + } else { + if #available(iOS 11.0, *) { + topOffset = CGPoint(x: 0, y: -self.adjustedContentInset.top) + } else { + topOffset = CGPoint(x: 0, y: -self.contentInset.top) + } + } + + // 确保在主线程执行 + DispatchQueue.main.async { + self.setContentOffset(topOffset, animated: animated) + } + } +} diff --git a/QuickLocation/Core/Extension/UITextField+Extensions.swift b/QuickLocation/Core/Extension/UITextField+Extensions.swift new file mode 100644 index 00000000..9ed97171 --- /dev/null +++ b/QuickLocation/Core/Extension/UITextField+Extensions.swift @@ -0,0 +1,27 @@ +// +// UITextField+Extensions.swift +// SHECommunity +// +// Created by psj on 2023/11/6. +// + +import Foundation +import UIKit + +extension UITextField { + func placeholderColor(placeholder: String, color: UIColor, font: UIFont = UIFont.systemFont(ofSize:15) ) { + // 字体大小 + self.attributedPlaceholder = NSAttributedString.init(string:placeholder, attributes: [NSAttributedString.Key.font:font]) + // 字体颜色 + self.attributedPlaceholder = NSAttributedString.init(string:placeholder, attributes: [NSAttributedString.Key.foregroundColor:color]) + } + + /// EZSE: Add left padding to the text in textfield + public func addLeftTextPadding(_ blankSize: CGFloat) { + let leftView = UIView() + leftView.frame = CGRect(x: 0, y: 0, width: blankSize, height: frame.height) + self.leftView = leftView + self.leftViewMode = UITextField.ViewMode.always + } + +} diff --git a/QuickLocation/Core/Extension/UIView+Extension.swift b/QuickLocation/Core/Extension/UIView+Extension.swift new file mode 100644 index 00000000..456463dc --- /dev/null +++ b/QuickLocation/Core/Extension/UIView+Extension.swift @@ -0,0 +1,347 @@ +// +// UIView+extension.swift +// Pubquiz +// +// Created by crow on 2018/6/4. +// Copyright © 2018年 xhy. All rights reserved. +// + +import Foundation +import UIKit + +public extension UIView { + + /// 设置边框和圆角 + /// - Parameters: + /// - radius: 圆角大学 + /// - color: 边框颜色,默认clear + /// - borderWidth: 边框线条宽度,默认0.5 + func setCornerRadius(_ radius: CGFloat, + color: UIColor = .clear, + borderWidth: CGFloat = 0.5) { + layer.masksToBounds = true + layer.cornerRadius = radius + layer.borderColor = color.cgColor + layer.borderWidth = borderWidth + } + + /// 自定义边角圆角,UIView确定frame后在设置 + /// - Parameters: + /// - corners: [.topLeft, .topRight, .bottomLeft, .bottomRight] + /// - size: 圆角大小 + func setCornerRadius(_ rect: CGRect = .zero, + corners: UIRectCorner, + withCornerRadii size: CGSize) { + // 圆角位置 + let roundedRect = rect == .zero ? bounds : rect + let maskPath = UIBezierPath(roundedRect: roundedRect, + byRoundingCorners: corners, + cornerRadii: size) + // 圆角大小 + let maskLayer = CAShapeLayer() + maskLayer.frame = roundedRect + maskLayer.path = maskPath.cgPath + layer.mask = maskLayer + } + + /// 设置阴影 + func setShadow(offset: CGSize, opacity: Float, radius: CGFloat, color: UIColor) { + self.layer.shadowColor = color.cgColor + self.layer.shadowOpacity = opacity + self.layer.shadowRadius = radius + self.layer.shadowOffset = offset + } + + /// 设置默认黑色阴影 + func addCommonShadow() { + setShadow(offset: .zero, + opacity: 0.1, + radius: 3, + color: UIColor.black.withAlphaComponent(0.2)) + } + + /// 设置视图外边距 + /// - Parameters: + /// - superView: 父视图 + /// - insets: UIEdgeInsets + @objc + func addAndConstraintTo(superView: UIView, + insets: UIEdgeInsets = .zero) { + self.translatesAutoresizingMaskIntoConstraints = false + superView.addSubview(self) + self.leadingAnchor.constraint(equalTo: superView.leadingAnchor, constant: insets.left).isActive = true + self.topAnchor.constraint(equalTo: superView.topAnchor, constant: insets.top).isActive = true + self.trailingAnchor.constraint(equalTo: superView.trailingAnchor, constant: insets.right).isActive = true + self.bottomAnchor.constraint(equalTo: superView.bottomAnchor, constant: insets.bottom).isActive = true + superView.layoutIfNeeded() + } + + static func removeExtraLineForTable(_ tableView: UITableView) { + let view = UIView() + tableView.tableFooterView = view + } + + /// 设置渐变色 + /// - Parameters: + /// - frame: frame + /// - startPoint: 开始点 + /// - endPoint: 结束点 + /// - colors: 颜色 + /// - locations: 位置 + func setGradientLayer(frame: CGRect, + startPoint: CGPoint, + endPoint: CGPoint, + colors: [UIColor], + locations: [CGFloat]) { + if let sublayers = self.layer.sublayers { + for layer in sublayers { + if layer.name == "Defalut_GradientLayer" { + layer.removeFromSuperlayer() + break + } + } + } + let gradientLayer = CAGradientLayer() + gradientLayer.name = "Defalut_GradientLayer" + gradientLayer.frame = frame + gradientLayer.startPoint = startPoint + gradientLayer.endPoint = endPoint + gradientLayer.colors = colors.compactMap { $0.cgColor } + gradientLayer.locations = locations.compactMap { NSNumber(value: $0) } +// layer.addSublayer(gradientLayer) + if let firstSublayer = layer.sublayers?.first { + layer.insertSublayer(gradientLayer, below: firstSublayer) + } else { + layer.addSublayer(gradientLayer) + } + } +} + +public extension UIView { + + /// 添加缩放动画 + /// - Parameters: + /// - duration: 动画时间 + /// - usingSpringWithDamping: TimeInterval + /// - initialSpringVelocity: CGFloat + func affineTransformScale(duration: TimeInterval, + usingSpringWithDamping: TimeInterval, + initialSpringVelocity: CGFloat) { + self.layer.setAffineTransform(CGAffineTransform(scaleX: 0.1, y: 0.1)) + + UIView.animate(withDuration: duration, delay: 0.01, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options:UIView.AnimationOptions.overrideInheritedOptions, animations: { () -> Void in + self.layer.setAffineTransform(CGAffineTransform(scaleX: 1, y: 1)) + }) { finished in + UIView.animate(withDuration: 0.08, animations:{ ()-> Void in + self.layer.setAffineTransform(.identity) + }) + } + } +} + +// MARK: - IBDesignable +@IBDesignable extension UIView { + @IBInspectable public var borderColor:UIColor? { + set { + layer.borderColor = newValue!.cgColor + } + get { + if let color = layer.borderColor { + return UIColor(cgColor:color) + } + else { + return nil + } + } + } + @IBInspectable public var borderWidth:CGFloat { + set { + layer.borderWidth = newValue + } + get { + return layer.borderWidth + } + } + @IBInspectable public var cornerRadius:CGFloat { + set { + layer.cornerRadius = newValue + clipsToBounds = newValue > 0 + } + get { + return layer.cornerRadius + } + } + @IBInspectable public var shadowOffset: CGSize { + set { + layer.shadowOffset = newValue + } + get { + return layer.shadowOffset + } + } + @IBInspectable public var shadowOpacity: Float { + set { + layer.shadowOpacity = newValue + } + get { + return layer.shadowOpacity + } + } + @IBInspectable public var shadowRadius: CGFloat { + set { + layer.shadowRadius = newValue + } + get { + return layer.shadowRadius + } + } + @IBInspectable public var shadowColor: UIColor? { + set { + layer.shadowColor = newValue?.cgColor + } + get { + if let color = layer.shadowColor { + return UIColor(cgColor:color) + } + else { + return nil + } + } + } +} + +// MARK: - Frame +public extension DLWrapper where Base: UIView { + + var height: CGFloat { + set { + var newframe = base.frame + newframe.size.height = newValue + base.frame = newframe + } + + get { base.frame.size.height } + } + + var width: CGFloat { + set { + var newframe = base.frame + newframe.size.width = newValue + base.frame = newframe + } + + get { base.frame.size.width } + } + + var x: CGFloat { + set { + var newframe = base.frame + newframe.origin.x = newValue + base.frame = newframe + } + + get { base.frame.origin.x } + } + + var y: CGFloat { + set { + var newframe = base.frame + newframe.origin.y = newValue + base.frame = newframe + } + + get { base.frame.origin.y } + } + + var size: CGSize { + set { + var newframe = base.frame + newframe.size = newValue + base.frame = newframe + } + + get { base.frame.size } + } + + var origin: CGPoint { + set { + var newframe = base.frame + newframe.origin = newValue + base.frame = newframe + } + + get { base.frame.origin } + } +} + +extension UIView { + + func findSubView(with tag: Int) -> UIView? { + subviews.first(where: { $0.tag == tag }) + } +} + +// MARK: - 生成二维码图片 +extension UIView { + func generateQRCodeImage(_ content: String, size: CGSize) -> UIImage? { + // 创建滤镜 + guard let filter = CIFilter(name: "CIQRCodeGenerator") else {return nil} + // 还原滤镜的默认属性 + filter.setDefaults() + // 设置需要生成的二维码数据 + let contentData = content.data(using: String.Encoding.utf8) + filter.setValue(contentData, forKey: "inputMessage") + // 从滤镜中取出生成的图片 + guard let ciImage = filter.outputImage else { return nil } + + let context = CIContext(options: nil) + let bitmapImage = context.createCGImage(ciImage, from: ciImage.extent) + + let colorSpace = CGColorSpaceCreateDeviceGray() + let bitmapContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue) + + //draw image + let scale = min(size.width / ciImage.extent.width, size.height / ciImage.extent.height) + bitmapContext!.interpolationQuality = CGInterpolationQuality.none + bitmapContext?.scaleBy(x: scale, y: scale) + bitmapContext?.draw(bitmapImage!, in: ciImage.extent) + + //保存bitmap到图片 + guard let scaledImage = bitmapContext?.makeImage() else { return nil } + + return UIImage(cgImage: scaledImage) + } +} + +// MARK: - 截图 +extension UIView { + func takeScreenshot() -> UIImage? { + let renderer = UIGraphicsImageRenderer(bounds: bounds) + return renderer.image { context in + layer.render(in: context.cgContext) + } + } +} + +extension UIView { + func stringPrefix(index: Int, text: String) -> String { + if text.count <= index { + return text + } else { + let index = text.index(text.startIndex, offsetBy: index) + let str = text.prefix(upTo: index) + return String(str) + } + } +} + +// MARK: - 时间戳 +extension UIView { + func getDateInterval2String(date: String) -> String { + let date = Date(timeIntervalSince1970: TimeInterval(date.double)) + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = "yyyy.MM.dd HH:mm:ss" + let dateString = dateFormatter.string(from: date) + return dateString + } +} diff --git a/QuickLocation/Core/Extension/UIViewController+Extension.swift b/QuickLocation/Core/Extension/UIViewController+Extension.swift new file mode 100644 index 00000000..3d25d48f --- /dev/null +++ b/QuickLocation/Core/Extension/UIViewController+Extension.swift @@ -0,0 +1,172 @@ +// +// UIViewController+Extension.swift +// DLSDK +// +// Created by osell on 2023/8/2. +// + +import Foundation +import UIKit +import URLNavigator + +extension UIViewController { + /// 获取当前显示的 View Controller + public static var topViewController: UIViewController? { + var keyWindow = UIApplication.keyWindow + if keyWindow == nil { + for window in UIApplication.shared.windows { + if window.isKeyWindow { + keyWindow = window + break + } + } + } + var vc = keyWindow?.rootViewController + while true { + if let nc = vc as? UINavigationController { + vc = nc.visibleViewController + } else if let tbc = vc as? UITabBarController { + if let svc = tbc.selectedViewController { + vc = svc + } else { + break + } + } else if let pvc = vc?.presentedViewController { + vc = pvc + } else { + break + } + } + + return vc + } +} + +public extension UIViewController { + + struct Key { + static var needLogin = "needLoginKey" + } + + /// 是否需要登录 + var isNeedLogin: Bool { + get { + objc_getAssociatedObject(self, &Key.needLogin) as? Bool ?? false + } + + set { + objc_setAssociatedObject(self, &Key.needLogin, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + +} + +// MARK: Storyboard +extension UIViewController { + /// 从 Storyboard 中获取 ViewController + public static func viewControllerWithIdentifier(_ id: String, storyboardName name: String) -> UIViewController { + let storyboard = UIStoryboard(name: name, bundle: nil) + return storyboard.instantiateViewController(withIdentifier: id) + } +} + +extension UIViewController { + class func currentViewController(base: UIViewController? = UIApplication.keyWindow?.rootViewController) -> UIViewController? { + var base = base + if base == nil { + for window in UIApplication.shared.windows { + if window.isKeyWindow { + base = window.rootViewController + break + } + } + } + if let nav = base as? UINavigationController { + return currentViewController(base: nav.visibleViewController) + } + + if let tab = base as? UITabBarController { + return currentViewController(base: tab.selectedViewController) + } + + if let presented = base?.presentedViewController { + return currentViewController(base: presented) + } + return base + } +} + + +// MARK: - Toast +extension UIViewController { + + static func showErrorToast(message: String) { + #if !SHARE_EXTENSION + // 查询当前ViewController是否存在HUD,存在则在隐藏 + if let topMostVC = UIViewController.topMost, + ProgressHUD.findProgressHUD(for: topMostVC.view) != nil { + ProgressHUD.dismiss(immediate: true, forController: topMostVC) + } + if message != "" { + ProgressHUD.showError(withStatus: message) + } + else { + ProgressHUD.dismiss() + } + #endif + } + +} + +// MARK: 导航 +extension UIViewController { + func addNavBack() { + let backBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 44)) + backBtn.setImage(UIImage(named: "navBack"), for: .normal) + backBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0) + backBtn.addTarget(self, action: #selector(back), for: .touchUpInside) + let leftItem = UIBarButtonItem(customView: backBtn) + self.navigationItem.leftBarButtonItem = leftItem +// self.navigationItem.leftMargin = 0 + } + @objc func back() { + self.navigationController?.popViewController(animated: true) + + } + /// 显示 view controller(根据当前上下文,自动选择 push 或 present 方式) + @objc + public class func showViewController(_ controller: UIViewController, animated flag: Bool) { + let topViewController = UIViewController.topViewController + if let navigationController = topViewController as? UINavigationController { + navigationController.pushViewController(controller, animated: flag) + } else if let navigationController = topViewController?.navigationController { + navigationController.pushViewController(controller, animated: flag) + } else { + topViewController?.present(controller, animated: flag, completion: nil) + } + } + + public static func presentController(_ controller: UIViewController, animated flag: Bool) { + let topViewController = UIViewController.topViewController + topViewController?.present(controller, animated: flag, completion: nil) + } + + /// 显示 view controller(根据当前上下文,自动选择 push 或 present 方式) + public func showViewControllerAnimated(_ animated: Bool) { + UIViewController.showViewController(self, animated: animated) + } + + /// 关闭 view controller(根据当前上下文,自动选择 pop 或 dismiss 方式) + public static func closeViewControllerAnimated(_ animated: Bool) { + UIViewController.topViewController?.closeViewControllerAnimated(animated) + } + + /// 关闭 view controller(根据当前上下文,自动选择 pop 或 dismiss 方式) + public func closeViewControllerAnimated(_ animated: Bool) { + if let controller = navigationController, controller.viewControllers.count > 1 { + controller.popViewController(animated: animated) + } else { + dismiss(animated: animated, completion: nil) + } + } +} diff --git a/QuickLocation/Core/Extension/URL+Extension.swift b/QuickLocation/Core/Extension/URL+Extension.swift new file mode 100644 index 00000000..13568a33 --- /dev/null +++ b/QuickLocation/Core/Extension/URL+Extension.swift @@ -0,0 +1,118 @@ +// +// URL+Extension.swift +// dinoGo +// +// Created by Lin on 2023/3/9. +// Copyright © 2023 dino. All rights reserved. +// + +import Foundation + +extension URL { + public var parametersFromQueryString : [String: String]? { + guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), + let queryItems = components.queryItems else { return nil } + return queryItems.reduce(into: [String: String]()) { (result, item) in + result[item.name] = item.value + } + } +} + +public extension URLComponents { + + ///查询对应参数值 + func queryValue(for key: String) -> String? { + return queryItems? + .first(where: { $0.name == key })? + .value + } + + ///追加查询参数 + mutating func appendingQueryParameters(_ parameters: [String: String]) -> URL { + queryItems = (queryItems ?? []) + parameters.map { URLQueryItem(name: $0, value: $1) } + return url! + } + + ///删除查询参数 + mutating func removingQueryParameters(for keys: [String]) -> URL { + var dic = [String: String]() + + queryItems? + .filter({ !keys.contains($0.name) }) + .forEach({ dic[$0.name] = $0.value }) + + queryItems = [] + dic.map { URLQueryItem(name: $0, value: $1) } + return url! + } + +} + + +public extension URL { + + ///查询对应参数值 + func queryValue(for key: String) -> String? { + return URLComponents(string: absoluteString)?.queryValue(for: key) + } + + ///追加查询参数 + func appendingQueryParameters(_ parameters: [String: String]) -> URL { + var components = URLComponents(url: self, resolvingAgainstBaseURL: true)! + return components.appendingQueryParameters(parameters) + } + + ///追加查询参数 + mutating func appendQueryParameters(_ parameters: [String: String]) { + self = appendingQueryParameters(parameters) + } + + func removingQueryParameters(for keys: [String]) -> URL { + var components = URLComponents(url: self, resolvingAgainstBaseURL: true)! + return components.removingQueryParameters(for: keys) + } + + ///删除查询参数 + mutating func removeQueryParameters(for keys: [String]) { + self = removingQueryParameters(for: keys) + } + + +} + +//@objc public extension NSURLComponents { +// +// ///查询参数 +// var queryParameters: [String: String]? { +// return (self as URLComponents).queryParameters +// } +// ///追加查询参数 +// func appendingQueryParameters(_ parameters: [String: String]) -> URL { +// queryItems = (queryItems ?? []) + parameters.map { URLQueryItem(name: $0, value: $1) } +// return url! +// } +// +// ///查询对应参数值 +// func queryValue(for key: String) -> String? { +// return (self as URLComponents).queryValue(for: key) +// } +//} + + +@objc public extension NSURL { + + ///查询对应参数值 + func queryValue(for key: String) -> String? { + return (self as URL).queryValue(for: key) + } + + ///追加查询参数 + func appendingQueryParameters(_ parameters: [String: String]) -> URL { + return (self as URL).appendingQueryParameters(parameters) + } + + ///删除查询参数 + func removingQueryParameters(for keys: [String]) -> URL { + return (self as URL).removingQueryParameters(for: keys) + } + +} diff --git a/QuickLocation/Core/Wrapper.swift b/QuickLocation/Core/Wrapper.swift new file mode 100644 index 00000000..048d8530 --- /dev/null +++ b/QuickLocation/Core/Wrapper.swift @@ -0,0 +1,77 @@ +// +// Wrapper.swift +// SHECommunity +// +// Created by 林 on 2024/11/25. +// + +import Foundation + +public class DL {} + +public class DLWrapper { + + /// 原始对象 + public private(set) var base: Base + + /// 初始化方法 + public init(_ base: Base) { + self.base = base + } + +} + +public protocol DLWrapperCompatible { + + /// 关联类型 + associatedtype WrapperBase + + /// 类包装器属性 + static var dl: DLWrapper.Type { get set } + + /// 对象包装器属性 + var dl: DLWrapper { get set } + +} + + +extension DLWrapperCompatible { + + /// 类包装器属性 + public static var dl: DLWrapper.Type { + get { DLWrapper.self } + set {} + } + + /// 对象包装器属性 + public var dl: DLWrapper { + get { DLWrapper(self) } + set {} + } + +} + +// MARK: - DLWrapperCompatible +extension Int: DLWrapperCompatible {} +extension Int8: DLWrapperCompatible {} +extension Int16: DLWrapperCompatible {} +extension Int32: DLWrapperCompatible {} +extension Int64: DLWrapperCompatible {} +extension UInt: DLWrapperCompatible {} +extension UInt8: DLWrapperCompatible {} +extension UInt16: DLWrapperCompatible {} +extension UInt32: DLWrapperCompatible {} +extension UInt64: DLWrapperCompatible {} +extension Float: DLWrapperCompatible {} +extension Double: DLWrapperCompatible {} +extension Bool: DLWrapperCompatible {} +extension String: DLWrapperCompatible {} +extension Data: DLWrapperCompatible {} +extension Date: DLWrapperCompatible {} +extension URL: DLWrapperCompatible {} +extension URLRequest: DLWrapperCompatible {} +extension Array: DLWrapperCompatible {} +extension Set: DLWrapperCompatible {} +extension Dictionary: DLWrapperCompatible {} +extension CGFloat: DLWrapperCompatible {} +extension NSObject: DLWrapperCompatible {} diff --git a/QuickLocation/Info.plist b/QuickLocation/Info.plist new file mode 100644 index 00000000..84d228c4 --- /dev/null +++ b/QuickLocation/Info.plist @@ -0,0 +1,14 @@ + + + + + UIAppFonts + + douyu.otf + + NSLocationWhenInUseUsageDescription + 需要获取您的位置信息以在地图上显示您的位置 + NSLocationAlwaysAndWhenInUseUsageDescription + 需要获取您的位置信息以在地图上显示您的位置 + + diff --git a/QuickLocation/Main/BaseModel/BaseModelNew.swift b/QuickLocation/Main/BaseModel/BaseModelNew.swift new file mode 100644 index 00000000..6c0cafe9 --- /dev/null +++ b/QuickLocation/Main/BaseModel/BaseModelNew.swift @@ -0,0 +1,109 @@ +// +// BaseModel.swift +// dinoGo +// +// Created by 林 on 2020/5/18. +// Copyright © 2020 Lin. All rights reserved. +// + +import Foundation +import ObjectMapper +import SwiftyJSON + +var transformInt: (Any?) -> Int? = { value in + switch value { + case let value as String: + return Int(value) + case let value as Int: + return value + case let value as Double: + return Int(value) + default: + return nil + } +} + +var transformStr: (Any?) -> String? = { value in + switch value { + case let value as String: + return value + case let value as Int: + return String(value) + case let value as Double: + return String(value) + default: + return nil + } +} + +var transformJSON: (Any?) -> JSON? = { value in + if let jsonString = value as? String { + return JSON(jsonString) + } + return nil +} + +var transformJsonStr: (Any?) -> String? = { value in + if let json = value as? JSON { + return json.string + } + return nil +} + +/// String >> Int +let kStrTransformInt = TransformOf(fromJSON: transformInt, + toJSON: transformStr) +/// Int >> String +let kIntTransformStr = TransformOf(fromJSON: transformStr, + toJSON: transformInt) + +/// JsonString >> Json +let kJsonStrTransformJson = TransformOf(fromJSON: transformJSON, + toJSON: transformJsonStr) + +protocol BaseModelProtocol: Mappable { + var status: Bool? { get } + var code: String? { get } + var status_code: Int? { get } + var message: String? { get } +} + +extension BaseModelProtocol { + + var status: Bool? { return nil } + var code: String? { return nil} + var status_code: Int? { return nil } + + var isSuccess: Bool { +// if let status = status, status == true { +// if let code = code, code == GatewayStatusCodeOld.success.rawValue { +// return true +// } +// +// } + + // 新API + if let status_code = status_code, status_code == GatewayStatusCode.success.rawValue { + return true + } + + return false + } + + +} + +enum BoolType: String { + + case `true` = "Y" + case `false` = "N" + + var boolValue: Bool { + switch self { + case .true: + return true + case .false: + return false + } + } +} diff --git a/QuickLocation/Main/BaseModel/ListModel.swift b/QuickLocation/Main/BaseModel/ListModel.swift new file mode 100644 index 00000000..fe2a828b --- /dev/null +++ b/QuickLocation/Main/BaseModel/ListModel.swift @@ -0,0 +1,53 @@ +// +// ListModel.swift +// dinoGo +// +// Created by 林 on 2020/5/29. +// Copyright © 2020 Lin. All rights reserved. +// + +import UIKit +import ObjectMapper + +protocol ListModelType: BaseModelProtocol { + associatedtype Item + var list: [Item] { get set } + var pagination: PaginationModel? { get set } +} + +struct ListModel: ListModelType where Item: Mappable { + var code, message: String? + var status: Bool? + // 当前页索引 + var pageIndex = 1 + // 每页大小 + var pageSize = 20 + // 总条数 + var count = 0 + // 总页数 + var page_count = 0 + // 数据列表 + var list: [Item] = [] + // 分页对象 + var pagination: PaginationModel? + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + status <- map["status"] + code <- map["code"] + message <- map["message"] + pageIndex <- map["pageIndex"] + pageSize <- map["pageSize"] + count <- map["count"] + page_count <- map["page_count"] + list <- map["rows"] + + pagination = PaginationModel(pageIndex: pageIndex, + pageSize: pageSize, + totalNum: count, + totalPage: page_count) + } +} diff --git a/QuickLocation/Main/BaseModel/PaginationModel.swift b/QuickLocation/Main/BaseModel/PaginationModel.swift new file mode 100644 index 00000000..0f321cfb --- /dev/null +++ b/QuickLocation/Main/BaseModel/PaginationModel.swift @@ -0,0 +1,37 @@ +// +// PaginationModel.swift +// dinoGo +// +// Created by 林 on 2020/6/1. +// Copyright © 2020 Lin. All rights reserved. +// + +import UIKit + +public struct PaginationModel { + + // 当前页索引 + var pageIndex = 1 + // 每页大小 + var pageSize = 20 + // 总条数 + var totalNum = 0 + // 总页数 + var totalPage = 0 + + init(pageIndex: Int, pageSize: Int, totalNum: Int, totalPage: Int) { + self.pageIndex = pageIndex + self.pageSize = pageSize + self.totalNum = totalNum + self.totalPage = totalPage + } + + init(pageSize: Int, totalNum: Int) { + self.pageSize = pageSize + self.totalNum = totalNum + } + + func hasMoreData() -> Bool { + return pageSize <= totalNum + } +} diff --git a/QuickLocation/Main/BaseModel/ResponseModel.swift b/QuickLocation/Main/BaseModel/ResponseModel.swift new file mode 100644 index 00000000..021255b8 --- /dev/null +++ b/QuickLocation/Main/BaseModel/ResponseModel.swift @@ -0,0 +1,30 @@ +// +// ResponseModel.swift +// dinoGo +// +// Created by 林 on 2020/5/18. +// Copyright © 2020 Lin. All rights reserved. +// + +import Foundation +import ObjectMapper + +struct ResponseModel: BaseModelProtocol { + // 状态码 + var code: String? + // 消息 + var message: String? + // + var data: [String : Any]? + // + var result: Any? + + init?(map: Map) {} + + mutating func mapping(map: Map) { + code <- (map["code"], kIntTransformStr) + message <- map["message"] + data <- map["data"] + result <- map["data"] + } +} diff --git a/QuickLocation/Main/BaseService/ListService.swift b/QuickLocation/Main/BaseService/ListService.swift new file mode 100644 index 00000000..565e2ebc --- /dev/null +++ b/QuickLocation/Main/BaseService/ListService.swift @@ -0,0 +1,312 @@ +// +// ListService.swift +// HealthyZG +// +// Created by 林 on 2020/5/29. +// Copyright © 2020 Lin. All rights reserved. +// + +import UIKit +import RxSwift +import Moya +import ObjectMapper +import RxDataSources +import RxSwiftExt + +protocol ListServiceType { + associatedtype BaseListModel where BaseListModel: Mappable + associatedtype BaseItem where BaseItem: Mappable +} + +typealias PagingTargetTransform = (Int) -> MultiTarget + +enum PagingRequestType { + case refresh + case more + case clear +} + +typealias RefreshResult = (status: RefreshStatus, isEmpty: Bool) + +/// ListType: 列表数据泛型类,例: ListService> +class ListService: ListServiceType where ListType: ListModelType, ListType.Item: Mappable { + typealias BaseListModel = ListType + typealias BaseItem = ListType.Item + + struct ListResponse { + var listModel: BaseListModel? + var items: [BaseItem] = [] + var pagination: PaginationModel? + var refreshStatus: RefreshStatus? + } + + private var page = 1 + private var isPaging = true + + var targetTransform: PagingTargetTransform + var request = PublishSubject() + var refreshResult: Observable { + let refreshResult = _listResponse.flatMap { listResponse -> Observable in + guard let refreshStatus = listResponse.refreshStatus else { + return Observable.empty() + } + return Observable.just((refreshStatus, listResponse.items.isEmpty)) + } + return Observable.merge(refreshResult, _refreshResult) + } + var listResponse: Observable { + return _listResponse + } + var response: Observable<[BaseItem]> { + let itemResponse = _listResponse.map { $0.items } + return Observable.merge(itemResponse, _localResponse) + } + var responseModel: Observable { + return _listResponse.flatMap { listResponse -> Observable in + guard let listModel = listResponse.listModel else { + return Observable.empty() + } + return Observable.just(listModel) + } + } + var pagination: Observable { + return _listResponse.map { $0.pagination } + } + + var error: Observable { + return _error.asObserver() + } + var executing: Observable { + return _executing.asObserver() + } + var isExecuting = false + var listResponseModel: ListResponse? + var listModel: BaseListModel? { + return listResponseModel?.listModel + } + var paginationModel: PaginationModel? { + return listResponseModel?.pagination + } + var items: [BaseItem] { + return listResponseModel?.items ?? [] + } + + private var _listResponse: Observable = .empty() + private let _localResponse = PublishSubject<[BaseItem]>() + private let _refreshResult = PublishSubject() + private let _error = PublishSubject() + private let _executing = PublishSubject() + + // MARK: API + var fileterMap: ((PagingRequestType) -> FilterMap) { + return { [unowned self] request -> FilterMap in + switch request { + case .refresh: + // 下拉刷新 + self.page = 1 + self.isExecuting = true + self._executing.onNext(self.isExecuting) + return .map(self.page) + case .more: + // 上拉加载更多 + if self.items.isEmpty { + self.page = 1 + } + self.page += 1 + self.isExecuting = true + self._executing.onNext(self.isExecuting) + return .map(self.page) + case .clear: + // 清空数据 + self.onNext([]) + return .ignore + } + } + } + var transform: ((Event) -> ListResponse) { + return { [weak self] (event) in + var listResponse = ListResponse() + if let items = self?.listResponseModel?.items { + listResponse.items = items + } + guard let self = self else { + return listResponse + } + switch event { + case let .next(newListModel): + listResponse.listModel = newListModel + // New data arrived + let newItems = newListModel.list + // Paging enable + if self.isPaging { + if self.page == 1 { + if newItems.isEmpty { + listResponse.items = [] + } else { + listResponse.items = newItems + } + } else { + listResponse.items.append(contentsOf: newItems) + } + // Paging info + listResponse.pagination = newListModel.pagination + if newListModel.pagination!.hasMoreData() { + listResponse.refreshStatus = .hasMoreData + } else { + listResponse.refreshStatus = .noMoreData + } + } else { + if newItems.isEmpty { + listResponse.items = [] + } else { + listResponse.items = newItems + } + listResponse.refreshStatus = .noMoreData + } + default: + break + } + self.listResponseModel = listResponse + return listResponse + } + } + var filter: ((Event) -> Bool) { + return { [weak self] (event) in + guard let self = self else { + return false + } + switch event { + case let .error(error): + if self.page != 1 { + self.page -= 1 + } + self.isExecuting = false + self._executing.onNext(self.isExecuting) + self._refreshResult.onNext((.invalidData, self.items.isEmpty)) + self._error.onNext(error) + return false + case .completed: + return false + case .next: + self.isExecuting = false + self._executing.onNext(self.isExecuting) + return true + } + } + } + + @available(*, deprecated, message: "将弃用,请使用init(newPaging: Bool = true, targetTransform: @escaping PagingTargetTransform)") + init(paging: Bool = true, targetTransform: @escaping PagingTargetTransform) { + self.isPaging = paging + self.targetTransform = targetTransform + + _listResponse = request.filterMap(self.fileterMap) + .map { [weak self] page -> MultiTarget in + guard let self = self else { return targetTransform(page) } + return self.targetTransform(page) + }.flatMapLatest { [weak self] api -> Observable in + guard let self = self else { + return Observable.empty() + } + return self.request(api: api) + .materialize() + .filter(self.filter) + .map(self.transform) + }.share(replay: 1) + } + + init(newPaging: Bool = true, targetTransform: @escaping PagingTargetTransform) { + self.isPaging = newPaging + self.targetTransform = targetTransform + + _listResponse = request.filterMap(self.fileterMap) + .map { [weak self] page -> MultiTarget in + guard let self = self else { return targetTransform(page) } + return self.targetTransform(page) + }.flatMapLatest { [weak self] api -> Observable in + guard let self = self else { + return Observable.empty() + } + return self.requestList(api: api) + .materialize() + .filter(self.filter) + .map(self.transform) + }.share(replay: 1) + } + + func request(api: MultiTarget) -> Observable { + if self.isPaging == false { + return APIProvider.request(token: api) + .map(ListType.self) + .asObservable() + } + + return APIProvider.request(token: api) + .map(ListType.self)//, atKeyPath: "result") + .asObservable() + } + + func requestList(api: MultiTarget) -> Observable { + if self.isPaging == false { + return APIProvider.request(token: api).map(ListType.self).asObservable() + } + return APIProvider.request(token: api).map(ListType.self).asObservable() + } + + func onNext(_ value: [BaseItem]) { + listResponseModel?.items = value + _localResponse.onNext(value) + } + +} + +// MARK: - Map array elements to animatable model +extension Array where Element: IdentifiableType & Equatable { + func mapAnimatableSection() -> [AnimatableSectionModel] { + guard !isEmpty else { return [] } + let newItems = removedDuplicates() + return [AnimatableSectionModel(model: "", items: newItems)] + } +} + +extension Array where Element: IdentifiableType { + func removedDuplicates() -> [Element] { + // remove duplicated item + var uuids = Set() + var newItems: [Element] = [] + for item in self { + let identity = item.identity + if !uuids.contains(identity) { + _ = uuids.insert(identity) + newItems.append(item) + } + } + return newItems + } +} + +// MARK: - Map array elements to section model +extension Array { + func mapSection() -> [SectionModel] { + guard !isEmpty else { return [] } + return [SectionModel(model: "", items: self)] + } +} + +// MARK: - Differ animatable section model +extension ListService where BaseItem: IdentifiableType & Equatable { + var animatableSectionedItems: Observable<[AnimatableSectionModel]> { + return response.map { items -> [AnimatableSectionModel] in + return items.mapAnimatableSection() + } + } +} + +// MARK: - Section model +extension ListService { + var sectionedItems: Observable<[SectionModel]> { + return response.map { items -> [SectionModel] in + return items.mapSection() + } + } +} diff --git a/QuickLocation/Main/BaseViewController/BaseNavigationController.swift b/QuickLocation/Main/BaseViewController/BaseNavigationController.swift new file mode 100644 index 00000000..135b392e --- /dev/null +++ b/QuickLocation/Main/BaseViewController/BaseNavigationController.swift @@ -0,0 +1,124 @@ +// +// BaseNavigationController.swift +// SHECommunity +// +// Created by 林 on 2024/11/25. +// + +import UIKit + +class BaseNavigationController: UINavigationController { + + var isPresented: Bool { + return viewControllers.count == 1 && presentingViewController != nil + } + + @objc func dismissClicked(_ item: UIBarButtonItem) { + self.navigationController?.dismiss(animated: true, completion: nil) + } + + @objc func leftBackClicked(_ item: UIBarButtonItem) { + self.navigationController?.popViewController(animated: true) + } + + func setupLeftItem() { + guard !isNavigationBarHidden else { return } + if isPresented { + let dismissItem = UIBarButtonItem(image: UIImage(named: "Common/close"), + style: .plain, + target: self, + action: #selector(dismissClicked(_:))) + navigationItem.leftBarButtonItem = dismissItem + } else if let count = navigationController?.viewControllers.count, count > 1 { + let leftBackItem = UIBarButtonItem(image: UIImage(named: "Common/back_white"), + style: .plain, + target: self, action: #selector(leftBackClicked(_:))) + navigationItem.leftBarButtonItem = leftBackItem + } + } + + func setNavibar() { +// self.navigationBar.barTintColor = Color.mainColor +// self.navigationBar.tintColor = .white +// self.navigationBar.shadowColor = Color.rgbCCCCCC + self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white, + NSAttributedString.Key.font:UIFont.systemFont(ofSize: 18, weight: .semibold)]; +// self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "", style: .plain, target: nil, action: nil); + } + + override var preferredStatusBarStyle: UIStatusBarStyle { + if let vc = self.viewControllers.last { + return vc.preferredStatusBarStyle + } else { + return .lightContent + } + } + + override func viewDidLoad() { + super.viewDidLoad() + setNavigationBarHidden(true, animated: false) +// if #available(iOS 13, *) { +// let appearance = UINavigationBarAppearance() +// appearance.configureWithOpaqueBackground() +//// appearance.backgroundImage = UIImage(named: "navigation-back-img") +// appearance.shadowImage = UIImage() +// appearance.shadowColor = Color.rgbCCCCCC +// appearance.backgroundColor = Color.mainColor +// appearance.titleTextAttributes = [NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 18), +// NSAttributedString.Key.foregroundColor:UIColor.white] +// navigationBar.standardAppearance = appearance +// navigationBar.scrollEdgeAppearance = navigationBar.standardAppearance +// } +// else { +// navigationBar.barTintColor = Color.mainColor +// navigationBar.tintColor = .white +// navigationBar.shadowColor = Color.rgbCCCCCC +// navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white, +// NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize:18)] +// +// } + + } + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + setNavigationBarHidden(true, animated: false) + } + + override func pushViewController(_ viewController: UIViewController, animated: Bool) { + + if self.viewControllers.count == 0 { + super.pushViewController(viewController, animated: animated) + return + } +// if let vc = viewController as? BaseViewController, vc.requireLogin() && !isLogin() { +// toLogin() +// return +// } +// self.setNavigationBarHidden(true, animated: false) + viewController.hidesBottomBarWhenPushed = true + super.pushViewController(viewController, animated: animated) + } + + override var shouldAutorotate: Bool { + if let vc = self.viewControllers.last { + return vc.shouldAutorotate + } else { + return false + } + } + override var supportedInterfaceOrientations: UIInterfaceOrientationMask { + if let vc = self.viewControllers.last { + return vc.supportedInterfaceOrientations + } else { + return .portrait + } + } + override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { + if let vc = self.viewControllers.last { + return vc.preferredInterfaceOrientationForPresentation + } else { + return .portrait + } + } + +} diff --git a/QuickLocation/Main/BaseViewController/BaseViewController.swift b/QuickLocation/Main/BaseViewController/BaseViewController.swift new file mode 100644 index 00000000..5e6905d3 --- /dev/null +++ b/QuickLocation/Main/BaseViewController/BaseViewController.swift @@ -0,0 +1,280 @@ +// +// BaseViewController.swift +// SHECommunity +// +// Created by 林 on 2024/11/25. +// + +import UIKit +import RxCocoa +import RxSwift +#if DEBUG || AdHoc +//import FLEX +#endif + +class BaseViewController: UIViewController { + + var disposeBag = DisposeBag() + /// 是否隐藏导航栏,默认false + var isNavigationBarHidden: Bool { true } + /// 目前配色: false主题色/true白色, 默认是false + var isChangeNavigationBarStyle: Bool { true } + /// 是否显示导航底部阴影, 默认是导航栏颜色,白色显示,主题色不显示 + var isShowNavigationBarShadow: Bool { isChangeNavigationBarStyle } + /// 状态栏样式,默认是default + override var preferredStatusBarStyle: UIStatusBarStyle { .default } + + var isPresented: Bool { + return navigationController?.viewControllers.count == 1 && + navigationController?.presentingViewController != nil + } + + /// 导航栏标题 + var navTitle: String = "" { + didSet { + backButton.setTitle(" \(navTitle)", for: .normal) +// navigationItem.title = navTitle + } + } + + override func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + fd_prefersNavigationBarHidden = isNavigationBarHidden + + view.backgroundColor = ThemeManager.shared.color.backgroundColor +// setupNavigationBar() + setupLeftItem() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + let className = String(describing: self.classForCoder) + print(className) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + + let className = String(describing: self.classForCoder) + print(className) + } + + @objc func dismissClicked(_ item: UIBarButtonItem) { + self.navigationController?.dismiss(animated: true, completion: nil) + } + + @objc func leftBackClicked(_ item: UIBarButtonItem) { + self.navigationController?.popViewController(animated: true) + } + + private func setupNavigationBar() { + let appearance = UINavigationBarAppearance() + appearance.configureWithOpaqueBackground() + appearance.backgroundImage = UIImage() + appearance.shadowImage = UIImage() + appearance.shadowColor = .clear + appearance.backgroundColor = ThemeManager.shared.color.backgroundColor + navigationController?.navigationBar.standardAppearance = appearance + navigationController?.navigationBar.scrollEdgeAppearance = appearance + } + + // MARK: - Left Item + func setupLeftItem() { + guard !isNavigationBarHidden else { return } + if isPresented { + let dismissItem = UIBarButtonItem(image: UIImage(named: "Common/close")?.adaptiveImage, + style: .plain, + target: self, + action: #selector(dismissClicked(_:))) + dismissItem.tintColor = .white + navigationItem.leftBarButtonItem = dismissItem + } else if let count = navigationController?.viewControllers.count, count > 1 { + let leftBarBtn = UIBarButtonItem (customView: backButton) + + //用于消除左边空隙,要不然按钮顶不到最前面 + let spacer = UIBarButtonItem (barButtonSystemItem: .fixedSpace, target: nil, action: nil) + spacer.width = -10 + navigationItem.leftBarButtonItem = leftBarBtn +// navigationItem.leftBarButtonItems = [spacer, leftBarBtn] +// let leftBackItem = UIBarButtonItem(image: UIImage(named: "Common/back"), +// style: .plain, +// target: self, action: #selector(leftBackClicked(_:))) +// leftBackItem.tintColor = .white +// navigationItem.leftBarButtonItem = leftBackItem + } + } + + lazy var backButton: UIButton = { + let button = UIButton (type: .custom) + button.frame = CGRectMake (0, 0, 200, 30) + button.setImage(UIImage(named: "Common/back"), for: .normal) + button.titleLabel?.font = .systemFont(ofSize: 18, weight: .medium) + button.contentHorizontalAlignment = .left + button.setTitleColor(ThemeManager.shared.color.titleColor, for: .normal) + button.addTarget(self, action: #selector(leftBackClicked(_:)), for: .touchUpInside) + return button + }() + +} + +// MARK: - 验证码 +extension BaseViewController { + func requestSmsCode(phone: String, + sendBtn: UIButton, + countDownService: CountDownService) { + DLToast.showLoading() + SystemService.sendSmsCode(phone: phone).subscribe(onNext: { [weak self] response in + DLToast.showSuccess(text: response.message ?? "发送成功") + guard let self = self else { return } + self.startCountDown(sendBtn, countDownService) + }, onError: { _ in }).disposed(by: disposeBag) + } + + private func startCountDown(_ sendBtn: UIButton, _ countDownService: CountDownService) { + countDownService.startTimer() + countDownService.currentTime.subscribe(onNext: { time in + DispatchQueue.main.async { + var timeStr = "" + if time == 0 { + sendBtn.isEnabled = true + sendBtn.isUserInteractionEnabled = true + timeStr = "获取验证码" + NSObject.cancelPreviousPerformRequests(withTarget: self) + } + else { + sendBtn.isEnabled = false + sendBtn.isUserInteractionEnabled = false + timeStr = "\(time.string)s" + } + sendBtn.setTitle(timeStr, for: .normal) + } + }).disposed(by: disposeBag) + } +} + +// MARK: - 查看大图 +extension BaseViewController { + func showBigImage(imgUrlList: [String], currentPage: Int, projectiveView: UIView?=nil) { +// var tempProjectiveView = projectiveView +// if tempProjectiveView == nil { +// tempProjectiveView = UIView(frame: CGRect(origin: CGPoint(x: kScreenWidth * 0.5, y: kScreenHeight), size: CGSize(width: 1, height: 1))) +// } +// var datas: [YBIBDataProtocol] = [] +// GlobalAsync { +// for mediaUrl in imgUrlList { +// // 网络视频 +// if mediaUrl.hasSuffix(".mp4") { +// let videoData = YBIBVideoData() +// videoData.videoURL = URL(string: mediaUrl) +// videoData.projectiveView = tempProjectiveView +// datas.append(videoData) +// } +// // 网络图片 +// else if mediaUrl.hasPrefix("http") { +// let imageData = YBIBImageData() +// imageData.imageURL = URL(string: mediaUrl) +// imageData.projectiveView = tempProjectiveView +// datas.append(imageData) +// } +// } +// MainAsync { +// // 预览图片/视频 +// let browser = YBImageBrowser() +// browser.dataSourceArray = datas +// browser.currentPage = currentPage +// browser.show() +// } +// } + } +} + +// MARK: - FLEX +extension BaseViewController { + private func setupFlex() { +#if DEBUG || AdHoc +// FLEXManager.shared.showExplorer() +#endif + } + + override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { + print("摇晃结束") + setupFlex() + } +} + +// MAKR: - UIView查看大图 +extension UIView { + func showBigImage(imgUrlList: [String], currentPage: Int, projectiveView: UIView?=nil) { +// var tempProjectiveView = projectiveView +// if tempProjectiveView == nil { +// tempProjectiveView = UIView(frame: CGRect(origin: CGPoint(x: kScreenWidth * 0.5, y: kScreenHeight), size: CGSize(width: 1, height: 1))) +// } +// var datas: [YBIBDataProtocol] = [] +// GlobalAsync { +// for mediaUrl in imgUrlList { +// // 网络视频 +// if mediaUrl.hasSuffix(".mp4") { +// let videoData = YBIBVideoData() +// videoData.videoURL = URL(string: mediaUrl) +// videoData.projectiveView = tempProjectiveView +// datas.append(videoData) +// } +// // 网络图片 +// else if mediaUrl.hasPrefix("http") { +// let imageData = YBIBImageData() +// imageData.imageURL = URL(string: mediaUrl) +// imageData.projectiveView = tempProjectiveView +// datas.append(imageData) +// } +// } +// MainAsync { +// // 预览图片/视频 +// let browser = YBImageBrowser() +// browser.dataSourceArray = datas +// browser.currentPage = currentPage +// browser.show() +// } +// } + } +} + +// MARK: - PagerView +enum ScrollState { + case scrolling + case pending + case ended +} + +enum LastDirection { + case up + case down +} + +class PagerScrollView: UIScrollView { + weak var panDelegate: UIGestureRecognizerDelegate? + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { + if let delegate = panDelegate { + if let result = delegate.gestureRecognizer?(gestureRecognizer, shouldRecognizeSimultaneouslyWith: otherGestureRecognizer) { + return result + } + } + return false + } +} + +class PagerTableView: UITableView { + weak var panDelegate: UIGestureRecognizerDelegate? + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { + if let delegate = panDelegate { + if let result = delegate.gestureRecognizer?(gestureRecognizer, shouldRecognizeSimultaneouslyWith: otherGestureRecognizer) { + return result + } + } + return false + } +} diff --git a/QuickLocation/Main/BaseViewModel/BaseViewModel.swift b/QuickLocation/Main/BaseViewModel/BaseViewModel.swift new file mode 100644 index 00000000..12333884 --- /dev/null +++ b/QuickLocation/Main/BaseViewModel/BaseViewModel.swift @@ -0,0 +1,23 @@ +// +// BaseViewModel.swift +// SHECommunity +// +// Created by 林 on 2024/11/25. +// + +import Foundation +import RxSwift + +class BaseViewModel { + let disposeBag = DisposeBag() + + init() {} +} + +protocol ViewModelType { + associatedtype Input + associatedtype Output + + var input: Input { get } + var output: Output { get } +} diff --git a/QuickLocation/Main/Tabbar/MainTabBarController.swift b/QuickLocation/Main/Tabbar/MainTabBarController.swift new file mode 100644 index 00000000..304c0ddd --- /dev/null +++ b/QuickLocation/Main/Tabbar/MainTabBarController.swift @@ -0,0 +1,89 @@ +// +// MainTabBarController.swift +// QuickLocation +// + +import UIKit + +final class MainTabBarController: UITabBarController { + + // MARK: - View Controllers + private lazy var locationNav = BaseNavigationController(rootViewController: HomeViewController()) + private lazy var exploreNav = BaseNavigationController(rootViewController: ViewController()) + private lazy var circlesNav = BaseNavigationController(rootViewController: ViewController()) + private lazy var mineNav = BaseNavigationController(rootViewController: MineViewController()) + + private lazy var navControllers: [BaseNavigationController] = { + [locationNav, exploreNav, circlesNav, mineNav] + }() + + // MARK: - Custom Tab Bar + private let customTabBar: QuickLocationTabBar = { + let items: [QuickLocationTabBar.TabItem] = [ + QuickLocationTabBar.TabItem( + title: "位置", + image: UIImage(named: "Tabbar/location"), + selectedImage: UIImage(named: "Tabbar/location_selected") + ), + QuickLocationTabBar.TabItem( + title: "探索", + image: UIImage(named: "Tabbar/explore"), + selectedImage: UIImage(named: "Tabbar/explore_selected") + ), + QuickLocationTabBar.TabItem( + title: "圈子", + image: UIImage(named: "Tabbar/group"), + selectedImage: UIImage(named: "Tabbar/group_selected") + ), + QuickLocationTabBar.TabItem( + title: "我的", + image: UIImage(named: "Tabbar/mine"), + selectedImage: UIImage(named: "Tabbar/mine_selected") + ) + ] + return QuickLocationTabBar(items: items) + }() + + // MARK: - Lifecycle + override func viewDidLoad() { + super.viewDidLoad() + + viewControllers = navControllers + tabBar.isHidden = true + + for nav in navControllers { + nav.delegate = self + } + + view.addSubview(customTabBar) + customTabBar.delegate = self + + customTabBar.translatesAutoresizingMaskIntoConstraints = false + let tabBarHeight = customTabBar.intrinsicContentSize.height + NSLayoutConstraint.activate([ + customTabBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), + customTabBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), + customTabBar.bottomAnchor.constraint(equalToConstant: view.bottomAnchor), + customTabBar.heightAnchor.constraint(equalToConstant: tabBarHeight) + ]) + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + view.bringSubviewToFront(customTabBar) + } +} + +// MARK: - QuickLocationTabBarDelegate +extension MainTabBarController: QuickLocationTabBarDelegate { + func tabBar(_ tabBar: QuickLocationTabBar, didSelectTabAt index: Int) { + selectedIndex = index + } +} + +// MARK: - UINavigationControllerDelegate +extension MainTabBarController: UINavigationControllerDelegate { + func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { + customTabBar.isHidden = navigationController.viewControllers.count > 1 + } +} diff --git a/QuickLocation/Main/Tabbar/QuickLocationTabBar.swift b/QuickLocation/Main/Tabbar/QuickLocationTabBar.swift new file mode 100644 index 00000000..e1da83c9 --- /dev/null +++ b/QuickLocation/Main/Tabbar/QuickLocationTabBar.swift @@ -0,0 +1,198 @@ +// +// QuickLocationTabBar.swift +// QuickLocation +// + +import UIKit + +protocol QuickLocationTabBarDelegate: AnyObject { + func tabBar(_ tabBar: QuickLocationTabBar, didSelectTabAt index: Int) +} + +final class QuickLocationTabBar: UIView { + + struct TabItem { + let title: String + let image: UIImage? + let selectedImage: UIImage? + + init(title: String, image: UIImage?, selectedImage: UIImage? = nil) { + self.title = title + self.image = image + self.selectedImage = selectedImage ?? image + } + } + + // MARK: - Design Constants (in iOS points, from Lanhu @2x 容器 2) + private let barContentHeight: CGFloat = 56 + private let containerCornerRadius: CGFloat = 28 + private let horizontalInset: CGFloat = 18 + private let iconSize: CGFloat = 32 + private let iconLabelSpacing: CGFloat = 4 + private let labelHeight: CGFloat = 11 + + private let selectedTextColor = UIColor(hexStr: "#1A1A1A") + private let unselectedTextColor = UIColor(hexStr: "#AAAAAA") + + private let selectedFont = UIFont(name: "PingFangSC-Semibold", size: 11) + ?? UIFont.systemFont(ofSize: 11, weight: .semibold) + private let unselectedFont = UIFont.systemFont(ofSize: 11, weight: .regular) + + // MARK: - Properties + weak var delegate: QuickLocationTabBarDelegate? + + private let items: [TabItem] + private var tabViews: [UIView] = [] + private let containerView = UIView() + + private(set) var selectedIndex: Int = 0 + + // MARK: - Init + init(items: [TabItem]) { + self.items = items + super.init(frame: .zero) + setupUI() + updateSelection(animated: false) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - Layout + override var intrinsicContentSize: CGSize { + CGSize(width: UIView.noIntrinsicMetric, height: barContentHeight + kSafeBottomMargin) + } + + // MARK: - Setup + private func setupUI() { + backgroundColor = .clear + + containerView.backgroundColor = .white + containerView.layer.cornerRadius = containerCornerRadius + containerView.layer.shadowColor = UIColor(red: 0.059, green: 0.157, blue: 0.275, alpha: 0.1).cgColor + containerView.layer.shadowOffset = .zero + containerView.layer.shadowRadius = 8 + containerView.layer.shadowOpacity = 1 + addSubview(containerView) + + for (index, item) in items.enumerated() { + let tabView = makeTabView(item: item, index: index) + containerView.addSubview(tabView) + tabViews.append(tabView) + } + + containerView.translatesAutoresizingMaskIntoConstraints = false + + NSLayoutConstraint.activate([ + containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: horizontalInset), + containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -horizontalInset), + containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -kSafeBottomMargin), + containerView.heightAnchor.constraint(equalToConstant: barContentHeight) + ]) + } + + private func makeTabView(item: TabItem, index: Int) -> UIView { + let view = UIView() + view.tag = index + view.backgroundColor = .clear + + let imageView = UIImageView(image: item.image?.withRenderingMode(.alwaysOriginal)) + imageView.contentMode = .scaleAspectFit + imageView.tag = 100 + view.addSubview(imageView) + + let label = UILabel() + label.text = item.title + label.font = unselectedFont + label.textColor = unselectedTextColor + label.textAlignment = .center + label.tag = 200 + view.addSubview(label) + + let tap = UITapGestureRecognizer(target: self, action: #selector(tabTapped(_:))) + view.addGestureRecognizer(tap) + + return view + } + + // MARK: - Actions + @objc private func tabTapped(_ gesture: UITapGestureRecognizer) { + guard let view = gesture.view else { return } + let index = view.tag + guard index != selectedIndex else { return } + selectedIndex = index + updateSelection(animated: true) + delegate?.tabBar(self, didSelectTabAt: index) + } + + // MARK: - Selection + func setSelectedIndex(_ index: Int, animated: Bool = true) { + guard index != selectedIndex, index >= 0, index < items.count else { return } + selectedIndex = index + updateSelection(animated: animated) + } + + private func updateSelection(animated: Bool) { + for (i, view) in tabViews.enumerated() { + let isSelected = i == selectedIndex + if let imageView = view.viewWithTag(100) as? UIImageView { + let img = isSelected ? items[i].selectedImage : items[i].image + imageView.image = img?.withRenderingMode(.alwaysOriginal) + } + if let label = view.viewWithTag(200) as? UILabel { + label.font = isSelected ? selectedFont : unselectedFont + label.textColor = isSelected ? selectedTextColor : unselectedTextColor + } + } + } + + override func layoutSubviews() { + super.layoutSubviews() + + let containerWidth = containerView.bounds.width + guard containerWidth > 0, !tabViews.isEmpty else { return } + + let tabWidth = containerWidth / CGFloat(tabViews.count) + let tabHeight = containerView.bounds.height + + let totalHeight = iconSize + iconLabelSpacing + labelHeight + let startY = (tabHeight - totalHeight) / 2 + + for (i, view) in tabViews.enumerated() { + view.frame = CGRect( + x: CGFloat(i) * tabWidth, + y: 0, + width: tabWidth, + height: tabHeight + ) + + if let imageView = view.viewWithTag(100) as? UIImageView { + imageView.frame = CGRect( + x: (tabWidth - iconSize) / 2, + y: startY, + width: iconSize, + height: iconSize + ) + } + + if let label = view.viewWithTag(200) as? UILabel { + label.frame = CGRect( + x: 0, + y: startY + iconSize + iconLabelSpacing, + width: tabWidth, + height: labelHeight + ) + } + } + } + + // MARK: - Hit Testing + override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + if containerView.frame.contains(point) { + return true + } + let extendedBounds = bounds.insetBy(dx: 0, dy: -kSafeBottomMargin) + return extendedBounds.contains(point) + } +} diff --git a/QuickLocation/Manager/Account/Account.swift b/QuickLocation/Manager/Account/Account.swift new file mode 100644 index 00000000..c0f894ae --- /dev/null +++ b/QuickLocation/Manager/Account/Account.swift @@ -0,0 +1,64 @@ +// +// Account.swift +// SHECommunity +// +// Created by 林 on 2024/11/27. +// + +import Foundation +import SwiftyUserDefaults +import ObjectMapper + +extension DefaultsKeys { + var userConfig: DefaultsKey { .init("UserConfig") } + var loginToken: DefaultsKey { .init("LoginToken") } + var searchHistory: DefaultsKey<[String: [String]]?> { .init("searchHistory") } + var locationHistory: DefaultsKey<[String: [[String: Any]]]?> { .init("locationHistory") } + var searchShopHistory: DefaultsKey<[String]> { .init("searchShopHistory", defaultValue: []) } + var searchOrderHistory: DefaultsKey<[String]> { .init("searchOrderHistory", defaultValue: []) } +} + +struct Account: Mappable { + var token: String? + var phone: String? + var name: String? + + init?(map: Map) { + + } + + init(token: String, phone: String, name: String) { + self.token = token + self.phone = phone + self.name = name + } + + mutating func mapping(map: Map) { + token <- map["sn"] + phone <- map["phone"] + name <- map["name"] + } +} + +struct LocationHistoryModel: Mappable { + + var latitude: CGFloat? + var longitude: CGFloat? + var placemark: String? + + init(latitude: CGFloat, longitude: CGFloat, placemark: String) { + self.latitude = latitude + self.longitude = longitude + self.placemark = placemark + } + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + latitude <- map["latitude"] + longitude <- map["longitude"] + placemark <- map["placemark"] + } +} diff --git a/QuickLocation/Manager/Account/AppContextManager.swift b/QuickLocation/Manager/Account/AppContextManager.swift new file mode 100644 index 00000000..2b7f3cc5 --- /dev/null +++ b/QuickLocation/Manager/Account/AppContextManager.swift @@ -0,0 +1,173 @@ +// +// AppContextManager.swift +// SHECommunity +// +// Created by 林 on 2024/11/27. +// + +import Foundation +import SwiftyUserDefaults + +class AppContextManager: NSObject { + static let shared = AppContextManager() + + private var loginAccount: UserConfigModel? + + var account: UserConfigModel? { + if let loginAccount = loginAccount { + return loginAccount + } + guard let jsonData = Defaults[\.userConfig] else { return nil } + guard let loginAccount = UserConfigModel(data: jsonData) else { return nil } + self.loginAccount = loginAccount + return loginAccount + } + + /// 是否游客 + var isGuest: Bool { + return account?.temp == true + } + /// token + var token: String { + account?.token ?? "" + } + /// 用户头像 + var userId: String { + account?.uid ?? "" + } + /// 用户头像 + var avater: String { + account?.avater ?? "" + } + /// 用户名 + var name: String { + account?.name ?? "" + } + /// 用户手机号 + var userPhone: String { + return account?.phone ?? "" + } + + @discardableResult + public func saveAccount(_ account: UserConfigModel) -> Bool { + var tmpAccount = account + if let token = account.token { + Defaults[\.loginToken] = token + } + else if let loginToken = Defaults[\.loginToken] { + tmpAccount.token = loginToken + } + + guard let jsonData = tmpAccount.toData() else { + return false + } + + Defaults[\.userConfig] = jsonData + loginAccount = tmpAccount + + return true + } + + public func saveToken(_ token: String) { + Defaults[\.loginToken] = token + } + + public func deleteAccount() { + Defaults[\.loginToken] = nil + Defaults[\.userConfig] = nil + loginAccount = nil + } +} + +extension AppContextManager { + public func saveLocationHistory(data: [String: Any]) { + guard let latitude = data["latitude"] as? CGFloat, + let longitude = data["longitude"] as? CGFloat else { return } + + guard let account = loginAccount, let userId = account.uid else { + DLToast.showError(text: "用户不存在") + return + } + + if let searchHistory = Defaults[\.locationHistory] { + var searchList: [[String: Any]] = searchHistory[userId] ?? [[:]] + for historyData in searchList { + // 记录存在 + if historyData["latitude"] as! CGFloat == latitude, + historyData["longitude"] as! CGFloat == longitude { + let sortList = searchList.sorted { (data1, data2) -> Bool in + if latitude == data1["latitude"] as! CGFloat, + longitude == data1["longitude"] as! CGFloat { + return true + } + return false + } + searchList = sortList + } + // 记录不存在 + else { + searchList.insert(data, at: 0) + } + } + let history: [String: [[String: Any]]] = [userId: searchList] + Defaults[\.locationHistory] = history + } + else { + let history: [String: [[String: Any]]] = [userId: [data]] + Defaults[\.locationHistory] = history + } + } + + public func cleanLocationHistory() { + if let account = loginAccount, let userId = account.uid { + let history: [String: [[String: Any]]] = [userId: []] + Defaults[\.locationHistory] = history + } + } + + public func saveSearchHistory(searchText: String) { + if let account = loginAccount, let userId = account.uid { + if let searchHistory = Defaults[\.searchHistory] { + var searchList: [String] = searchHistory[userId] ?? [] + if searchList.contains(searchText) { + let sortList = searchList.sorted { (text1, text2) -> Bool in + if searchText == text1 { + return true + } + return false + } + searchList = sortList + } + else { + searchList.insert(searchText, at: 0) + } + let history: [String: [String]] = [userId: searchList] + Defaults[\.searchHistory] = history + } + else { + let history: [String: [String]] = [userId: [searchText]] + Defaults[\.searchHistory] = history + } + } + } + + public func deleteSearchHistory(searchText: String) { +// if let account = loginAccount, let userId = account.id { +// if let userSearchHistory = Defaults[\.userSearchHistory] { +// var searchList: [String] = userSearchHistory[userId] ?? [] +// if searchList.contains(searchText) { +// searchList.removeObject(searchText) +// } +// let history: [String: [String]] = [userId: searchList] +// Defaults[\.userSearchHistory] = history +// } +// } + } + + public func clearnSearchHistory() { + if let account = loginAccount, let userId = account.uid { + let history: [String: [String]] = [userId: []] + Defaults[\.searchHistory] = history + } + } +} diff --git a/QuickLocation/Manager/Account/UserConfigModel.swift b/QuickLocation/Manager/Account/UserConfigModel.swift new file mode 100644 index 00000000..3b037d70 --- /dev/null +++ b/QuickLocation/Manager/Account/UserConfigModel.swift @@ -0,0 +1,35 @@ +// +// UserConfigModel.swift +// QuickLocation +// +// Created by 八条 on 2026/5/26. +// + +import ObjectMapper +import RxDataSources + +struct UserConfigModel: Mappable { + var token: String? + var phone: String? + var name: String? + var avater: String? + + /// 是否游客 + var temp: Bool = true + + /// 用户 ID + var uid: String? + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + token <- map["token"] + temp <- map["temp"] + phone <- map["phone"] + name <- map["name"] + uid <- map["user_id"] + avater <- map["avater"] + } +} diff --git a/QuickLocation/Manager/Account/UserConfigResponse.swift b/QuickLocation/Manager/Account/UserConfigResponse.swift new file mode 100644 index 00000000..ea501885 --- /dev/null +++ b/QuickLocation/Manager/Account/UserConfigResponse.swift @@ -0,0 +1,44 @@ +// +// UserConfigResponse.swift +// QuickLocation +// +// Created by 八条 on 2026/5/26. +// + +import ObjectMapper + +class UserConfigResponse: BaseModelProtocol { + var code: String? + + var message: String? + + var model: UserConfigModel? + + required init?(map: Map) { + + } + + func mapping(map: Map) { + code <- map["code"] + message <- map["message"] + model <- map["data"] + } +} + +class UserLoginRespons: BaseModelProtocol { + var code: String? + + var message: String? + + var model: UserConfigModel? + + required init?(map: Map) { + + } + + func mapping(map: Map) { + code <- map["code"] + message <- map["message"] + model <- map["data"] + } +} diff --git a/QuickLocation/Manager/App/ApiManager.swift b/QuickLocation/Manager/App/ApiManager.swift new file mode 100644 index 00000000..fa98662e --- /dev/null +++ b/QuickLocation/Manager/App/ApiManager.swift @@ -0,0 +1,262 @@ +// +// ApiManager.swift +// SHECommunity +// +// Created by 林 on 2024/11/26. +// + +import SwiftyUserDefaults +import Moya +import SwiftyJSON +import RxSwift +import CommonCrypto + +class ApiManager: NSObject { + + public static let shared = ApiManager() + + let disposeBag = DisposeBag() + + var ignoreCheck: Bool = false + + /// firebase + var fcmToken: String? +} + +// MARK: - NetworkConfig +extension ApiManager { + /// 初始化 + func setup() { + setupNetworkConfig() + } + /// 初始化网络配置 + func setupNetworkConfig() { + AppNetworkConfig.shared.baseURL = URLManager.shared.apiServerURL + AppNetworkConfig.shared.httpHeader = { [weak self] in self?.httpHeader() ?? [:] } + AppNetworkConfig.shared.handleRespone = { [weak self] (result, isShowErrorToast) in + guard let this = self else { return nil } + return this.handleResult(result, handle: isShowErrorToast) + } + } + + /// HttpHeader + func httpHeader() -> [String: String] { + var headers: [String : String] = [:] + headers["Accept"] = "application/json" +// headers["Content-Type"] = "application/json" + + headers["x-platform"] = "ios" + headers["x-channel"] = "ios" + headers["x-mobile-brand"] = "ios" + headers["x-app-id"] = "10057" + headers["x-version"] = kAppShortVersion + headers["x-device-id"] = ApiManager.getMD5ID() + // 机型 + var systemInfo = utsname() + uname(&systemInfo) + let platform = withUnsafePointer(to: &systemInfo.machine.0) { ptr in + return String(cString: ptr) + } + headers["x-mobile-model"] = platform + + if let loginToken = Defaults[\.loginToken] { + headers["x-token"] = loginToken + } + + return headers + } + + // MARK: - 接口验证 + private func handleResult(_ result: Result, handle: Bool) -> Result? { + DLToast.dismiss() + switch result { + case let .success(response): + // 处理加密响应 + let decryptedData = ApiManager.decryptIfNeeded(response.data) + // response转json + let json = JSON(decryptedData ?? response.data) + print("============== decrypt ====================") + print(json) + let code = json["code"].int + let message = json["message"].string + let combineMessage = message ?? "请检查网络连接" + + // 接口code + switch code { + case GatewayStatusCode.success.rawValue: + // 如果有解密数据,返回解密后的 Response + if let decrypted = decryptedData { + let decryptedResponse = Response(statusCode: response.statusCode, + data: decrypted, + request: response.request, response: response.response) + return .success(decryptedResponse) + } + return result +// case GatewayStatusCode.outdateVersion.rawValue: // 版本过低 +// handleOutdateVersion(message) + case GatewayStatusCode.userLoginExpair.rawValue: // token失效 + handleTokenExpired(msg: message) + case GatewayStatusCode.noAuthority.rawValue: // 退出当前界面 + handlePopView(message) + default: + /// 统一提示错误 + let code = GatewayStatusCode(rawValue: code ?? -9999) ?? .unknownError + if code == .unknownError, handle { + DLToast.show(text: combineMessage) + } + } + return .failure(handleError(with: code, domain: "Data Error", message: combineMessage, data: response)) + case let .failure(error): + let message = error.gatewayMessage ?? "请检查网络连接" + if error.innerError?.code == NSURLErrorCancelled { + // 处理手动取消请求,打印日志 + LogInfo("cancel response: error: \(error.localizedDescription)") + } else if handle { + DLToast.show(text: message) + } + let innerError = error.innerError ?? error as NSError + return .failure(handleError(with: innerError.code, domain: innerError.domain, message: message)) + } + } + + private func handleError(with code: Int?, + domain: String, + message: String, + isShowTip: Bool = true, + data: Response? = nil) -> MoyaError { + // 处理错误信息 + let responseError = NSError(domain: domain, + code: code ?? -999999, + userInfo: [NSLocalizedDescriptionKey: message, + "isShowTip": isShowTip]) + let error = MoyaError.underlying(responseError, data) + return error + } + + // MARK: - 处理Token过期 + private func handleTokenExpired(msg: String?) { + MainAsync { + AppContextManager.shared.deleteAccount() +// IMServiceManager.shared.logout() + DLToast.showError(text: msg ?? "登录失效,请重新登录!") { +// AppDelegate.shared.showMainViewController() + } + } + } + + // MARK: - 业务中断(需退出当前页面) + private func handlePopView(_ msg: String?) { + MainAsync { + DLToast.showInfo(text: msg ?? "Error...") { + guard let viewController = UIViewController.currentViewController() else { return } + viewController.navigationController?.popViewController(animated: true) + } + } + } +} + +extension ApiManager { + // MARK: - AES-256-CBC 解密 + private static let jieMiKey = "0b0d7962d67a76f00cf9fe0eec0061c2" + private static let jieMiIV = String(jieMiKey.prefix(16)) + + /// 响应解密:如果 encrypt == 1,则解密 data 字段并返回 JSON Data + class func decryptIfNeeded(_ responseData: Data) -> Data? { + guard let json = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any], + let encrypt = json["encrypt"] as? Int, + encrypt == 1, + let encryptedString = json["data"] as? String, + let decryptedString = aes256CBCDecrypt(encryptedString, key: jieMiKey, iv: jieMiIV), + let decryptedData = decryptedString.data(using: .utf8), + let decryptedJSON = try? JSONSerialization.jsonObject(with: decryptedData) as? [String: Any] + else { return nil } + + return try? JSONSerialization.data(withJSONObject: decryptedJSON) + } + + private class func aes256CBCDecrypt(_ base64String: String, key: String, iv: String) -> String? { + guard let data = Data(base64Encoded: base64String), + let keyData = key.data(using: .utf8), + let ivData = iv.data(using: .utf8) else { return nil } + + let bufferSize = data.count + kCCBlockSizeAES128 + var buffer = [UInt8](repeating: 0, count: bufferSize) + var numBytesDecrypted = 0 + + let status = keyData.withUnsafeBytes { keyBytes in + ivData.withUnsafeBytes { ivBytes in + data.withUnsafeBytes { dataBytes in + CCCrypt( + CCOperation(kCCDecrypt), + CCAlgorithm(kCCAlgorithmAES), + CCOptions(kCCOptionPKCS7Padding), + keyBytes.baseAddress, kCCKeySizeAES256, + ivBytes.baseAddress, + dataBytes.baseAddress, data.count, + &buffer, bufferSize, + &numBytesDecrypted + ) + } + } + } + + guard status == kCCSuccess else { return nil } + return String(data: Data(bytes: buffer, count: numBytesDecrypted), encoding: .utf8) + } + + class func getMD5ID() -> String { + var strback = "" + strback = "\(getFileTime())-\(getSysU())" + + if strback.count < 6 { + strback = UIDevice.current.identifierForVendor?.uuidString ?? "" + } + + return getMd5_32Bit_String(strback, isUppercase: false) + } + + class func getMd5_32Bit_String(_ srcString: String, isUppercase: Bool) -> String { + let cStr = srcString.cString(using: .utf8) + let length = CC_LONG(strlen(cStr!)) + var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) + + CC_MD5(cStr, length, &digest) + + var result = "" + for i in 0.. String { + var info = stat() + let result = stat("/var/mobile", &info) + guard result == 0 else { + return "" + } + let time = info.st_birthtimespec + return String(format: "%ld.%09ld", time.tv_sec, time.tv_nsec) + } + + class func getSysU() -> String? { + let information = "L3Zhci9tb2JpbGUvTGlicmFyeS9Vc2VyQ29uZmlndXJhdGlvblByb2ZpbGVzL1B1YmxpY0luZm8vTUNNZXRhLnBsaXN0" + + guard let data = Data(base64Encoded: information), + let dataString = String(data: data, encoding: .utf8) else { + return nil + } + + do { + let fileAttributes = try FileManager.default.attributesOfItem(atPath: dataString) + if let date = fileAttributes[.creationDate] as? Date { + return String(format: "%.6f", date.timeIntervalSince1970) + } + } catch { + print("获取文件属性失败:\(error)") + } + + return nil + } +} diff --git a/QuickLocation/Manager/App/AppSettings.swift b/QuickLocation/Manager/App/AppSettings.swift new file mode 100644 index 00000000..b157c94d --- /dev/null +++ b/QuickLocation/Manager/App/AppSettings.swift @@ -0,0 +1,66 @@ +// +// AppSettings.swift +// SHECommunity +// +// Created by Lin on 2024/12/25. +// + +import UIKit +import RxSwift +import SwiftKeychainWrapper +import Network + +class AppSettings: NSObject { + + fileprivate static let kSharedSettingsKey = "DefaultUserSettings" + + let disposeBag = DisposeBag() + + static let shared: AppSettings = { + let appSettings: AppSettings + if let savedData = UserDefaults.standard.object(forKey: AppSettings.kSharedSettingsKey) as? Data, + let defaultSettings = NSKeyedUnarchiver.unarchiveObject(with: savedData) as? AppSettings { + appSettings = defaultSettings + } else { + appSettings = AppSettings() + } + appSettings.uuid = appSettings.getUUID() + return appSettings + }() + + /// AppStore ID + var appId: String { "" } + + /// UUID + var uuid: String = "" + + /// UniversalLink + public static let kAppsUniversalLink: String = "https://api.xxxx.com/xxxx/" + + // MARK: - 第三方SDK Key + /// 高德 + public static let kAppsAMapAppId = "4f6b29cfedc0e117316b88008fa41c07" + /// wechat + public static let kAppsWXApiAppId = "wx9c91710269dcd0cf" + /// 支付宝 + public static let kAppsAlipayAppId = "2021005110694730" + /// 个推 + public static let kAppsGeTuiAppId = "cYHNI4KThh6SxZUsf9RiU2" + +} + +// MARK: - UUID & Keychain +extension AppSettings { + private func getUUID() -> String { + if let retrievedString = KeychainWrapper.standard.string(forKey: "ShareUUIDKey") { + return retrievedString + } + return saveUUID() + } + + private func saveUUID() -> String { + let uuid = UIDevice.current.identifierForVendor!.uuidString + let saveSuccessful: Bool = KeychainWrapper.standard.set(uuid, forKey: "ShareUUIDKey") + return saveSuccessful ? uuid : "" + } +} diff --git a/QuickLocation/Manager/App/Authorize.swift b/QuickLocation/Manager/App/Authorize.swift new file mode 100644 index 00000000..d41d41ea --- /dev/null +++ b/QuickLocation/Manager/App/Authorize.swift @@ -0,0 +1,405 @@ +// +// Authorize.swift +// DLSDK +// +// Created by osell on 2023/8/3. +// + +import UIKit +import CoreLocation +import Photos +import AVFoundation +import UserNotifications +import AdSupport +import AppTrackingTransparency +import URLNavigator + + +// MARK: - AuthorizeType +/// 权限类型枚举 +@objc(DLAuthorizeType) +public enum AuthorizeType: Int { + /// 使用时定位,Info.plist需配置NSLocationWhenInUseUsageDescription + case locationWhenInUse = 1 + /// 后台定位,Info.plist需配置NSLocationAlwaysUsageDescription和NSLocationAlwaysAndWhenInUseUsageDescription + case locationAlways = 2 + /// 麦克风,需启用Microphone子模块,Info.plist需配置NSMicrophoneUsageDescription + case microphone = 3 + /// 相册,Info.plist需配置NSPhotoLibraryUsageDescription + case photoLibrary = 4 + /// 照相机,Info.plist需配置NSCameraUsageDescription + case camera = 5 + /// 联系人,需启用Contacts子模块,Info.plist需配置NSContactsUsageDescription + case contacts = 6 + /// 日历,需启用Calendar子模块,Info.plist需配置NSCalendarsUsageDescription + case calendars = 7 + /// 提醒,需启用Calendar子模块,Info.plist需配置NSRemindersUsageDescription + case reminders = 8 + /// 音乐,需启用AppleMusic子模块,Info.plist需配置NSAppleMusicUsageDescription + case appleMusic = 9 + /// 通知,远程推送需打开Push Notifications开关和Background Modes的Remote notifications开关 + case notifications = 10 + /// 广告跟踪,需启用Tracking子模块,Info.plist需配置NSUserTrackingUsageDescription + case tracking = 11 +} + +// MARK: - AuthorizeStatus +/// 权限状态枚举 +@objc(DLAuthorizeStatus) +public enum AuthorizeStatus: Int { + /// 未确认 + case notDetermined = 0 + /// 受限制 + case restricted = 1 + /// 被拒绝 + case denied = 2 + /// 已授权 + case authorized = 3 +} + +// MARK: - AuthorizeProtocol +/// 权限授权协议 +@objc(DLAuthorizeProtocol) +public protocol AuthorizeProtocol { + /// 查询权限状态,必须实现。某些权限会阻塞当前线程,建议异步查询,如通知 + func authorizeStatus() -> AuthorizeStatus + + /// 执行权限授权,主线程回调,必须实现 + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) + + /// 异步查询权限状态,当前线程回调,可选实现。某些权限建议异步查询,不会阻塞当前线程,如通知 + @objc optional func authorizeStatus(_ completion: ((AuthorizeStatus) -> Void)?) +} + +// MARK: - AuthorizeManager +/// 权限管理器。由于打包上传ipa时会自动检查隐私库并提供Info.plist描述,所以默认关闭隐私库声明 +/// +@objc(DLAuthorizeManager) +@objcMembers public class AuthorizeManager: NSObject { + private static var managers: [AuthorizeType: AuthorizeProtocol] = [:] + private static var blocks: [AuthorizeType: () -> AuthorizeProtocol] = [:] + + /// 获取指定类型的权限管理器单例,部分权限未启用时返回nil + public static func manager(type: AuthorizeType) -> AuthorizeProtocol? { + if let manager = managers[type] { return manager } + guard let manager = factory(type: type) else { return nil } + managers[type] = manager + return manager + } + + /// 注册指定类型的权限管理器创建句柄,用于动态扩展权限类型 + public static func registerAuthorize(_ type: AuthorizeType, withBlock block: @escaping () -> AuthorizeProtocol) { + blocks[type] = block + } + + private static func factory(type: AuthorizeType) -> AuthorizeProtocol? { + if let block = blocks[type] { + return block() + } + + switch type { + case .locationWhenInUse: + return AuthorizeLocation(isAlways: false) + case .locationAlways: + return AuthorizeLocation(isAlways: true) + case .photoLibrary: + return AuthorizePhotoLibrary() + case .camera: + return AuthorizeCamera() + case .notifications: + return AuthorizeNotifications() + case .microphone: + return AuthorizeMicrophone() + case .tracking: + return AuthorizeTracking() + default: + return nil + } + } + + static func openAppSetting(title: String, message: String) { + let alertVC = UIAlertController.init(title: title, + message: message, + preferredStyle: .alert) + let cancelAction = UIAlertAction.init(title: "取消", style: .cancel) + let setAction = UIAlertAction.init(title: "去设置", style: .default) { action in + guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { + return + } + if UIApplication.shared.canOpenURL(settingsURL) { + UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) + } + } + alertVC.addAction(cancelAction) + alertVC.addAction(setAction) + + UIViewController.topMost?.present(alertVC, animated: true, completion: nil) + } +} + +// MARK: - AuthorizeLocation +/// 定位授权 +private class AuthorizeLocation: NSObject, AuthorizeProtocol, CLLocationManagerDelegate { + private lazy var locationManager: CLLocationManager = { + let result = CLLocationManager() + result.delegate = self + return result + }() + + private var completionBlock: ((AuthorizeStatus) -> Void)? + private var changeIgnored: Bool = false + private var isAlways: Bool = false + + init(isAlways: Bool) { + super.init() + self.isAlways = isAlways + } + + func authorizeStatus() -> AuthorizeStatus { + // 定位功能未打开时返回Denied,可自行调用[CLLocationManager locationServicesEnabled]判断 + let status = CLLocationManager.authorizationStatus() + switch status { + case .restricted: + return .restricted + case .denied: + return .denied + case .authorizedAlways: + return .authorized + case .authorizedWhenInUse: + if isAlways { + let isAuthorized = UserDefaults.standard.object(forKey: "DLAuthorizeLocation") + return isAuthorized != nil ? .denied : .notDetermined + } else { + return .authorized + } + default: + return .notDetermined + } + } + + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) { + completionBlock = completion + + if isAlways { + locationManager.requestAlwaysAuthorization() + // 标记已请求授权 + UserDefaults.standard.set(NSNumber(value: 1), forKey: "DLAuthorizeLocation") + UserDefaults.standard.synchronize() + } else { + locationManager.requestWhenInUseAuthorization() + } + } + + func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { + // 如果请求always权限且当前已经是WhenInUse权限,系统会先回调此方法一次,忽略之 + if isAlways && !changeIgnored { + if status == .notDetermined || status == .authorizedWhenInUse { + changeIgnored = true + return + } + } + + // 主线程回调,仅一次 + if completionBlock != nil { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + self.completionBlock?(self.authorizeStatus()) + self.completionBlock = nil + } + } + } +} + +// MARK: - AuthorizePhotoLibrary +/// 相册授权 +private class AuthorizePhotoLibrary: NSObject, AuthorizeProtocol { + func authorizeStatus() -> AuthorizeStatus { + let status = PHPhotoLibrary.authorizationStatus() + switch status { + case .restricted: + return .restricted + case .denied: + return .denied + case .authorized: + return .authorized + default: + return .notDetermined + } + } + + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) { + PHPhotoLibrary.requestAuthorization { status in + if completion != nil { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + completion?(self.authorizeStatus()) + } + } + } + } +} + +// MARK: - AuthorizeCamera +/// 照相机授权 +private class AuthorizeCamera: NSObject, AuthorizeProtocol { + func authorizeStatus() -> AuthorizeStatus { + // 模拟器不支持照相机,返回受限制 + let mediaType = AVMediaType.video + guard let device = AVCaptureDevice.default(for: mediaType) else { return .restricted } + if !device.hasMediaType(mediaType) { return .restricted } + + let status = AVCaptureDevice.authorizationStatus(for: mediaType) + switch status { + case .restricted: + return .restricted + case .denied: + return .denied + case .authorized: + return .authorized + default: + return .notDetermined + } + } + + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) { + AVCaptureDevice.requestAccess(for: .video) { granted in + if completion != nil { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + completion?(self.authorizeStatus()) + } + } + } + } +} + +// MARK: - AuthorizeNotifications +/// 通知授权 +private class AuthorizeNotifications: NSObject, AuthorizeProtocol { + func authorizeStatus() -> AuthorizeStatus { + var status: AuthorizeStatus = .notDetermined + // 由于查询授权为异步方法,此处使用信号量阻塞当前线程,同步返回查询结果 + let semaphore = DispatchSemaphore(value: 0) + UNUserNotificationCenter.current().getNotificationSettings { settings in + switch settings.authorizationStatus { + case .denied: + status = .denied + case .authorized: + status = .authorized + case .provisional: + status = .authorized + default: + status = .notDetermined + } + semaphore.signal() + } + semaphore.wait() + return status + } + + func authorizeStatus(_ completion: ((AuthorizeStatus) -> Void)?) { + UNUserNotificationCenter.current().getNotificationSettings { settings in + var status: AuthorizeStatus = .notDetermined + switch settings.authorizationStatus { + case .denied: + status = .denied + case .authorized: + status = .authorized + case .provisional: + status = .authorized + default: + status = .notDetermined + } + + if completion != nil { + DispatchQueue.main.async { + completion?(status) + } + } + } + } + + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) { + let options: UNAuthorizationOptions = [.badge, .sound, .alert] + UNUserNotificationCenter.current().requestAuthorization(options: options) { granted, error in + let status: AuthorizeStatus = granted ? .authorized : .denied + if completion != nil { + DispatchQueue.main.async { + completion?(status) + } + } + } + UIApplication.shared.registerForRemoteNotifications() + } +} + +// MARK: - AuthorizeMicrophone +/// 麦克风授权 +private class AuthorizeMicrophone: NSObject, AuthorizeProtocol { + func authorizeStatus() -> AuthorizeStatus { + let status = AVAudioSession.sharedInstance().recordPermission + switch status { + case .denied: + return .denied + case .granted: + return .authorized + default: + return .notDetermined + } + } + + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) { + AVAudioSession.sharedInstance().requestRecordPermission { granted in + let status: AuthorizeStatus = granted ? .authorized : .denied + if completion != nil { + DispatchQueue.main.async { + completion?(status) + } + } + } + } +} + +// MARK: - AuthorizeTracking +/// IDFA授权,iOS14+使用AppTrackingTransparency,其它使用AdSupport +class AuthorizeTracking: NSObject, AuthorizeProtocol { + func authorizeStatus() -> AuthorizeStatus { + if #available(iOS 14.0, *) { + let status = ATTrackingManager.trackingAuthorizationStatus + switch status { + case .restricted: + return .restricted + case .denied: + return .denied + case .authorized: + return .authorized + default: + return .notDetermined + } + } else { + return ASIdentifierManager.shared().isAdvertisingTrackingEnabled ? .authorized : .denied + } + } + + func authorize(_ completion: ((AuthorizeStatus) -> Void)?) { + if #available(iOS 14.0, *) { + ATTrackingManager.requestTrackingAuthorization { status in + if completion != nil { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + completion?(self.authorizeStatus()) + } + } + } + } else { + if completion != nil { + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + completion?(self.authorizeStatus()) + } + } + } + } +} + + diff --git a/QuickLocation/Manager/App/FileTools.swift b/QuickLocation/Manager/App/FileTools.swift new file mode 100644 index 00000000..bc94d6c4 --- /dev/null +++ b/QuickLocation/Manager/App/FileTools.swift @@ -0,0 +1,28 @@ +// +// FileTools.swift +// SHECommunity +// +// Created by Lin on 2024/12/9. +// + +import UIKit + +class FileTools: NSObject { + + /// 读取json文件 + static func readJSONFromFile(fileName: String) -> [String: Any]? { + if let fileURL = Bundle.main.url(forResource: fileName, withExtension: "json") { + do { + let jsonData = try Data(contentsOf: fileURL) + let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) + if let jsonDictionary = jsonObject as? [String: Any] { + // 处理得到的 JSON 字典 + return jsonDictionary + } + } catch { + print("读取 JSON 文件发生错误: \(error)") + } + } + return nil + } +} diff --git a/QuickLocation/Manager/App/Permission.swift b/QuickLocation/Manager/App/Permission.swift new file mode 100644 index 00000000..777ee8ec --- /dev/null +++ b/QuickLocation/Manager/App/Permission.swift @@ -0,0 +1,160 @@ +// +// Permission.swift +// JiuLaiBao +// +// Created by SeanXu on 2018/10/26. +// Copyright © 2018 DemoOrg. All rights reserved. +// + +import UIKit +import UserNotifications +import AVFoundation +import URLNavigator +import Photos + +class Permission: NSObject { + + public typealias Callback = (Bool) -> Void + public typealias SetAction = () -> Void + + static func notificationAuthorizationStatus(_ callback: @escaping Callback) { + if #available(iOS 10.0, *) { + UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in + DispatchQueue.main.async { + switch settings.authorizationStatus { + case .authorized, .provisional: + callback(true) + case .denied: + callback(false) + default: + break + } + } + }) + } else { + if UIApplication.shared.currentUserNotificationSettings?.types.isEmpty == false { + callback(true) + } else { + callback(false) + } + } + } + +// static func openAppSetting(title: String, message: String, cancelHandle: ((PopupAction) -> Void)? = nil ) { +// let popupVC = PopupViewController(title: title, detail: message, +// cancelTitle: "取消", +// cancelHandler: cancelHandle, +// confirmTitle: "前往设置") { _ in +// guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { +// return +// } +// if UIApplication.shared.canOpenURL(settingsURL) { +// if #available(iOS 10.0, *) { +// UIApplication.shared.open(settingsURL) { _ in } +// } else { +// UIApplication.shared.openURL(settingsURL) +// } +// } +// } +// UIViewController.topMost?.present(popupVC, animated: true, completion: nil) +// } + + static func openAppSetting(title: String, message: String, setAction: SetAction?=nil) { + let alertVC = UIAlertController.init(title: title, + message: message, + preferredStyle: .alert) + let cancelAction = UIAlertAction.init(title: "取消", style: .cancel) + + let setAction = UIAlertAction.init(title: "去设置", style: .default) { action in + if let setAction = setAction { + setAction() + return + } + guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { + return + } + if UIApplication.shared.canOpenURL(settingsURL) { + UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) + } + } + alertVC.addAction(cancelAction) + alertVC.addAction(setAction) + + UIViewController.topMost?.present(alertVC, animated: true, completion: nil) + } + + static func photosAuthorizationStatus(_ callback: @escaping Callback) { + PHPhotoLibrary.requestAuthorization { (status) in + switch status { + case .authorized: + DispatchQueue.main.async { + callback(true) + } + case .notDetermined, .denied, .restricted: + DispatchQueue.main.async { + callback(false) + } + default: + break + } + } + } + + static func cameraAuthorizationStatus(_ callback: @escaping Callback) { + AVCaptureDevice.requestAccess(for: .video) { status in + DispatchQueue.main.async { + callback(status) + } + } + } +} + +// CameraAuthHelper +typealias CameraEnableHandle = (_ enable: Bool, _ first: Bool) -> Void +class CameraAuth { + func cameraEnable(completion: @escaping CameraEnableHandle) { + guard UIImagePickerController.isSourceTypeAvailable(.camera) else { + completion(false, false) + return + } + let authStatus = AVCaptureDevice.authorizationStatus(for: .video) + if authStatus == .authorized { + completion(true, false) + } else if authStatus == .denied { + completion(false, false) + } else if authStatus == .restricted { + completion(false, false) + } else if authStatus == .notDetermined { + AVCaptureDevice.requestAccess(for: .video, completionHandler: { (firstState) in + completion(firstState, true) + }) + } + } + + func openSystemLight(open: Bool, device: AVCaptureDevice?) { + guard let device = device else {return} + if device.hasTorch { + do { + try device.lockForConfiguration() + device.torchMode = open ? .on : .off + device.unlockForConfiguration() + } catch { + print("电筒失败\(error)") + } + } + } + + // 扫描image 二维码 + func scanImageRQCode(image: UIImage) -> String? { + let ciImage: CIImage = CIImage(image: image)! + let context = CIContext(options: nil) + let detector = CIDetector(ofType: CIDetectorTypeQRCode, + context: context, + options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) + let features = detector?.features(in: ciImage) + guard let results = features, + !results.isEmpty, + let qrText = results.first as? CIQRCodeFeature else { return nil} + return qrText.messageString ?? nil + } +} diff --git a/QuickLocation/Manager/App/RouterManager.swift b/QuickLocation/Manager/App/RouterManager.swift new file mode 100644 index 00000000..ffc31fa1 --- /dev/null +++ b/QuickLocation/Manager/App/RouterManager.swift @@ -0,0 +1,100 @@ +// +// AppRouter.swift +// dinoGo +// +// Created by osell on 2023/2/8. +// Copyright © 2023 dino. All rights reserved. +// + +// MARK: - Route +import URLNavigator +enum Route: String { + /// web + case web = "web" + /// 登录 + case login = "login" +} + +extension Route: RouterTarget { + + var scheme: String { "jsdw://" } + + var name: String { "" } + + var path: String { rawValue } +} + +// MARK: - AppRouter +extension AppRouter: AppRouterProtocol { + + public func setupHandlerRouter() { + AppRouter.globalRouteHandler { route, userInfo in + guard let url = URL(string: route), + let scheme = url.scheme else { + DLToast.showError(text: "oapp_RouteError".localizedString) + return false + } + + // https/http链接 + if scheme == "https" || scheme == "http" { + var params = userInfo ?? [String: String]() + let query = url.queryParameters + params = params.merging(query ?? [:], uniquingKeysWith: { value1, _ in return value1 }) + if params["browesr"].safeString == "2" { + // 打开外部浏览器 + UIApplication.shared.open(url) + } else { + // 打开内部浏览器 + params["url"] = url.absoluteString + AppRouter.push(Route.web, userInfo: params) + } + return false + } + + // 系统内部 + if ["tel", "telprompt", "sms", "mailto"].contains(where: { $0 == scheme.lowercased() }) { + UIApplication.shared.open(url) + return false + } + + guard let vc = AppRouter.viewController(route, userInfo: userInfo) else { + DLToast.showError(text: "请检查路由") + return false + } + + if vc.isNeedLogin && !AppContextManager.shared.isGuest { +// AppRouter.push(Route.login) + return false + } + + return true + } + } + + public func setupRegisterRouter() { + // MARK: - web +// AppRouter.register(Route.web) { url, parameters in +// guard let urlStr = parameters["url"] as? String, +// let url = URL(string: urlStr)?.absoluteString else { return nil } +// let params = parameters.compactMap { +// guard $0.key != "url" else { +// return nil +// } +// return "\($0.key)=\(String(describing: $0.value))" +// }.joined(separator: "&") +// let separator = url.contains("?") ? "&" : "?" +// let tempUrl = url + separator + params +// let style = parameters["style"].safeString +// let isShare = parameters["isShare"].safeString == "1" ? true : false +// let fullscreen = parameters["fullscreen"].safeString == "1" ? true : false +// return WebViewController(url: tempUrl, isShare: isShare, fullscreen: fullscreen, style: style.isEmpty ? "default" : style) +// } + + // MARK: - 登录 + AppRouter.register(Route.login) { url, parameters in + LoginViewController() + } + } +} + + diff --git a/QuickLocation/Manager/CountDown/CountDownService.swift b/QuickLocation/Manager/CountDown/CountDownService.swift new file mode 100644 index 00000000..06d7627d --- /dev/null +++ b/QuickLocation/Manager/CountDown/CountDownService.swift @@ -0,0 +1,71 @@ +// +// CountDownService.swift +// HealthyZG +// +// Created by 林 on 2020/8/11. +// Copyright © 2020 Lin. All rights reserved. +// + +import RxSwift + +class CountDownService { + + /// 仅用来做token刷新倒计时 + static let shared = CountDownService(countDownTime: 1800) + + private var disposeBag = DisposeBag() + private var time = 0 + private var countDownTime: Int + + var timer: DispatchSourceTimer? + var currentTime = PublishSubject() + + init(countDownTime: Int) { + self.countDownTime = countDownTime + time = countDownTime + } + + func cancelTimer() { + timer?.cancel() + timer = nil + } + + func startTimer() { + time += 1 + + if timer == nil { + let queue = DispatchQueue.global() + timer = DispatchSource.makeTimerSource(queue: queue) + timer?.schedule(deadline: .now(), repeating: .seconds(1)) + } + + timer?.setEventHandler(handler: { [weak self] in + guard let `self` = self else { return } + self.countDown() + }) + timer?.resume() + } + + func countDown() { + time -= 1 + if time == 0 { + cancelTimer() + currentTime.onNext(time) + time = countDownTime + } else { + currentTime.onNext(time) + } + } +} + +// MARK: - Token刷新倒计时 +extension CountDownService { + func tokenRefreshCountDown() { + + } + + func tokenRefreshStop() { + cancelTimer() + time = countDownTime + } +} diff --git a/QuickLocation/Manager/Money/MoneyFormatter.swift b/QuickLocation/Manager/Money/MoneyFormatter.swift new file mode 100644 index 00000000..a860b7a6 --- /dev/null +++ b/QuickLocation/Manager/Money/MoneyFormatter.swift @@ -0,0 +1,26 @@ +// +// MoneyFormatter.swift +// SHECommunity +// +// Created by Lin on 2024/12/24. +// + +import UIKit + +class MoneyFormatter: NSObject { + + static let shared = MoneyFormatter() + + func verifyFormat(money: String) -> String { + var tempValue = money + // 处理是否保留小数点后面的数值 + var lastStr = "" + // 处理支持小数点的金额 + if let dotIndex = tempValue.firstIndex(of: ".") { + lastStr = String(tempValue.suffix(from: dotIndex)).replacingOccurrences(of: ".", with: "") + lastStr = "." + lastStr.prefix(2) + tempValue = String(tempValue.prefix(upTo: dotIndex)) + } + return tempValue + lastStr + } +} diff --git a/QuickLocation/Manager/Notification/TimeSpecificNotificationManager.swift b/QuickLocation/Manager/Notification/TimeSpecificNotificationManager.swift new file mode 100644 index 00000000..bf1d5a79 --- /dev/null +++ b/QuickLocation/Manager/Notification/TimeSpecificNotificationManager.swift @@ -0,0 +1,126 @@ +// +// TimeSpecificNotificationManager.swift +// SHECommunity +// +// Created by Lin on 2025/7/29. +// + +import UIKit +import UserNotifications + +class TimeSpecificNotificationManager { + static let shared = TimeSpecificNotificationManager() + private init() {} + + // 1. 请求通知权限(必须先调用) + func requestNotificationPermission() { + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in + if granted { + print("通知权限已允许") + } else { + print("通知权限被拒绝,无法发送通知") + } + } + } + + // 2. 发送指定时间的本地通知(一次性) + /// - Parameters: + /// - title: 通知标题 + /// - body: 通知内容 + /// - date: 触发的具体日期时间(如 2025-08-01 09:30:00) + /// - identifier: 通知唯一标识(用于后续取消等操作) + func scheduleOneTimeNotification( + title: String, + body: String, + at date: Date, + identifier: String = UUID().uuidString + ) { + // 创建通知内容 + let content = UNMutableNotificationContent() + content.title = title + content.body = body + content.sound = .default // 通知声音 + content.badge = 1 // 应用图标角标 + + // 将 Date 转换为 DateComponents(提取年月日时分) + let components = Calendar.current.dateComponents( + [.year, .month, .day, .hour, .minute], // 精确到分钟(忽略秒和毫秒) + from: date + ) + + // 创建日历触发器(一次性) + let trigger = UNCalendarNotificationTrigger( + dateMatching: components, + repeats: false // 仅触发一次 + ) + + // 创建通知请求 + let request = UNNotificationRequest( + identifier: identifier, + content: content, + trigger: trigger + ) + + // 添加通知到系统 + UNUserNotificationCenter.current().add(request) { error in + if let error = error { + print("通知添加失败:\(error.localizedDescription)") + } else { + print("通知已设置,将在 \(date) 触发") + } + } + } + + // 3. 发送重复的指定时间通知(如每天同一时间) + /// - Parameters: + /// - title: 通知标题 + /// - body: 通知内容 + /// - hour: 小时(24小时制,如 9 表示上午9点) + /// - minute: 分钟(如 30 表示30分) + /// - identifier: 通知唯一标识 + func scheduleRepeatingNotification( + title: String, + body: String, + hour: Int, + minute: Int, + identifier: String = UUID().uuidString + ) { + let content = UNMutableNotificationContent() + content.title = title + content.body = body + content.sound = .default + content.badge = 1 + + // 设置触发时间(忽略年/月/日,仅保留时/分,配合 repeats: true 实现每天重复) + var dateComponents = DateComponents() + dateComponents.hour = hour // 例如:9(上午9点) + dateComponents.minute = minute // 例如:30(30分) + + // 创建日历触发器(每天重复) + let trigger = UNCalendarNotificationTrigger( + dateMatching: dateComponents, + repeats: true // 重复触发(根据 dateComponents 中的粒度,此处为每天) + ) + + // 添加通知请求 + let request = UNNotificationRequest( + identifier: identifier, + content: content, + trigger: trigger + ) + + UNUserNotificationCenter.current().add(request) { error in + if let error = error { + print("重复通知添加失败:\(error.localizedDescription)") + } else { + print("每天 \(hour):\(minute) 的重复通知已设置") + } + } + } + + // 4. 取消指定标识的通知(用于取消已设置的定时通知) + func cancelNotification(identifier: String) { + UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier]) + print("已取消标识为 \(identifier) 的通知") + } +} diff --git a/QuickLocation/Manager/Theme/ThemeManager.swift b/QuickLocation/Manager/Theme/ThemeManager.swift new file mode 100644 index 00000000..9059632c --- /dev/null +++ b/QuickLocation/Manager/Theme/ThemeManager.swift @@ -0,0 +1,122 @@ +// +// ThemeManager.swift +// SHECommunity +// +// Created by 林 on 2024/11/28. +// + +import UIKit +import SwiftyUserDefaults +import ObjectMapper + +extension DefaultsKeys { + var themeColor: DefaultsKey { .init("ThemeColor") } + var themeFont: DefaultsKey { .init("ThemeFont") } +} + +public class ThemeManager: NSObject { + public static let shared = ThemeManager() + + private var themeColor = ThemeColor() + private var themeFont = ThemeFont() + + public var color: ThemeColor { + guard let jsonData = Defaults[\.themeColor] else { return themeColor } + guard let themeColor = ThemeColor(data: jsonData) else { return self.themeColor } + self.themeColor = themeColor + return themeColor + } + + public var font: ThemeFont { + guard let jsonData = Defaults[\.themeFont] else { return themeFont } + guard let themeFont = ThemeFont(data: jsonData) else { return self.themeFont } + self.themeFont = themeFont + return themeFont + } + + /// 配置默认主题色、主题字体 + public func configure(themeColor: ThemeColor?=nil, themeFont: ThemeFont?=nil) { + if let color = themeColor { + self.themeColor = color + } + if let font = themeFont { + self.themeFont = font + } + } +} + +public struct ThemeColor: Mappable { + /// 主色 + public var mainColor = UIColor(hexStr: "#7AD6FF") + /// 辅助色 + public var auxColor = UIColor(hexStr: "#F9BC0C") + /// 导航栏标题颜色 + public var navBarTitleColor = UIColor(hexStr: "#333333") + /// 页面标题、板块标题、选中后文字色 + public var titleColor = UIColor(hexStr: "#1F1613") + public var titleAuxColor = UIColor(hexStr: "#333333") + /// 用于二级页面重要功能操作入口 描述性文字 + public var subTitleColor = UIColor(hexStr: "#666666") + /// 用于次要信息、辅助功能,如提示说明文字 搜索栏默认文字 #999999 + public var contentColor = UIColor(hexStr: "#999999") + /// 线条 + public var lineColor = UIColor(hexStr: "#F2F2F2") + /// 背景色 + public var backgroundColor = UIColor(hexStr: "#F2F2F2") + /// 商品卡片背景色 + public var itemBackgroundColor = UIColor(hexStr: "#FFFFFF") + /// 文字背景色(文字为主色需要背景时专用) + public var textBackgroundColor = UIColor(hexStr: "#22A356") + /// 按钮disabled颜色(线条、背景、文字) + public var buttonDisabledColor = UIColor(hexStr: "#E6E6E6") + + /// 智慧物业主色 + public var propertyMainColor = UIColor(hexStr: "#2B67FF") + + public init() { + + } + + public init?(map: Map) { + + } + + public mutating func mapping(map: Map) { + mainColor <- map["mainColor"] + auxColor <- map["auxColor"] + titleColor <- map["titleColor"] + titleAuxColor <- map["titleAuxColor"] + subTitleColor <- map["subTitleColor"] + contentColor <- map["contentColor"] + lineColor <- map["lineColor"] + backgroundColor <- map["backgroundColor"] + itemBackgroundColor <- map["itemBackgroundColor"] + textBackgroundColor <- map["textBackgroundColor"] + buttonDisabledColor <- map["buttonDisabledColor"] + } +} + +public struct ThemeFont: Mappable { + /// + public var navBarFont = UIFont.systemFont(ofSize: 18, weight: .bold) + /// + public var titleFont = UIFont.systemFont(ofSize: 16, weight: .bold) + /// + public var contentFont = UIFont.systemFont(ofSize: 12, weight: .regular) + public var subContentFont = UIFont.systemFont(ofSize: 10, weight: .regular) + + public init() { + + } + + public init?(map: Map) { + + } + + public mutating func mapping(map: Map) { + navBarFont <- map["navBarFont"] + titleFont <- map["titleFont"] + contentFont <- map["contentFont"] + subContentFont <- map["subContentFont"] + } +} diff --git a/QuickLocation/Manager/URL/URLManager.swift b/QuickLocation/Manager/URL/URLManager.swift new file mode 100644 index 00000000..c942dd51 --- /dev/null +++ b/QuickLocation/Manager/URL/URLManager.swift @@ -0,0 +1,127 @@ +// +// URLManager.swift +// SHECommunity +// +// Created by 林 on 2024/11/26. +// + +import Foundation +import SwiftyUserDefaults +import RxSwift + +extension DefaultsKeys { + // 接口环境 0:测试环境 1:正式环境 + var apiEnvKey: DefaultsKey { .init("ApiEnvKey", defaultValue: -99) } + // 接口地址 + var apiServerURL: DefaultsKey { .init("ApiServerURL", defaultValue: "") } +} + +@objcMembers class URLManager: NSObject { + static let shared = URLManager() + + // -1: UAT 0: 开发 1: 正式 + var apiEnv: Int = 0 + /// 接口地址 + var apiServerURL: String = "" { + didSet { + AppNetworkConfig.shared.baseURL = apiServerURL + } + } + + /// 用户协议 + var userAgreementUrl: String { "https://sd.zuom8.cn/Agreement.html" } + /// 隐私政策 + var privacyPolicyUrl: String { "https://sd.zuom8.cn/Privacy.html" } + /// 注销须知 + var cancellationNoticeUrl: String { "https://h5.yiwen618.com.cn/yiwen_h5_logoff.html" } + /// 在线客服 + var onlineCustomerServiceUrl: String { "https://h5.zywmwl.com/kefu.html" } + /// 建议有奖规则 + var feedbackRuleUrl: String { "https://h5.zywmwl.com/suggestion_rule.html" } + /// 使用说明 + var useGuideUrl: String { "https://activity.zywmwl.com/web_acitvtiy/#/pages/index/useGoldDetail" } + +// /// 物流跟踪 +// var orderTrackUrl: String { "\(apiServerURL)/webapp/h5/dist/index.html#/order-track" } +// /// 延误赔付详情 +// var delayDetailUrl: String { "\(apiServerURL)/webapp/delayedpayment/detail.html" } +// /// FAQ +// var faqUrl: String { "\(apiServerURL)/webapp/faq/detail.html?service_im_id=\(IMService.shared.customServiceId)" } +// /// CRM +// var crmUrl: String { apiServerURL + "/webapp/h5/dist/index.html#/crm/bd" } + + private override init() { + super.init() + self.setupNetworkMode() + } + + func setupNetworkMode() { + #if DEBUG + setupApiEnv(1) + #elseif AdHoc + setupApiEnv(-1) + #else + setupApiEnv(1) + #endif + } + + private func setupApiEnv(_ env: Int) { + // env + if Defaults[\.apiEnvKey] != -99 { + apiEnv = Defaults[\.apiEnvKey] + } + else { + apiEnv = env + } + // api + if Defaults[\.apiServerURL].isEmpty { + apiServerURL = apiServerURL(apiEnv) + } else { + apiServerURL = Defaults[\.apiServerURL] + } + } + + // MARK: - 接口地址 + func apiServerURL(_ env: Int) -> String { + switch env { + case 1: // 正式 + return "https://jsapi.zuom8.cn/" + case -1: // UAT + return "https://jsapi.zuom8.cn/" + default: // SIT + return "https://jsapi.zuom8.cn/" + } + } + + // MARK: - 大对象服务器地址 + func uploadServerURL() -> String { +//#if DEBUG +// return "" +//#else + return "" +//#endif + } + + // MARK: - 设置h5参数 + func setupUrlParams(_ strUrl: String) -> String { + var tempUrl = strUrl + let separator = strUrl.contains("?") ? "&" : "?" + tempUrl.append(separator) + // 状态栏高度 + var params = ["height=\(kStatusBarHeight)"] + // 经纬度 + if let latitude = Defaults[\.currentLatitude], + let longitude = Defaults[\.currentLongitude] { + params.append("lat=\(latitude)") + params.append("log=\(longitude)") + } + // header + if let ecommerceHeader = ApiManager.shared.httpHeader()["EcommerceHeader"] { + params.append("header=\(ecommerceHeader)") + } + if let paramsStr = params.joined(separator: "&").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { + tempUrl.append(paramsStr) + } + return tempUrl + } +} diff --git a/QuickLocation/Model/SystemResponse.swift b/QuickLocation/Model/SystemResponse.swift new file mode 100644 index 00000000..089e92ba --- /dev/null +++ b/QuickLocation/Model/SystemResponse.swift @@ -0,0 +1,27 @@ +// +// SystemResponse.swift +// QuickLocation +// +// Created by 八条 on 2026/5/26. +// + +import Foundation +import ObjectMapper + +/// 验证码 +struct SmsCodeResponse: BaseModelProtocol { + // 状态码 + var code: String? + // 消息 + var message: String? + // + var result: Any? + + init?(map: Map) {} + + mutating func mapping(map: Map) { + code <- map["code"] + message <- map["msg"] + result <- map["data"] + } +} diff --git a/QuickLocation/Plugin/ImagePlugin.swift b/QuickLocation/Plugin/ImagePlugin.swift new file mode 100644 index 00000000..366fab52 --- /dev/null +++ b/QuickLocation/Plugin/ImagePlugin.swift @@ -0,0 +1,169 @@ +// +// ImagePlugin.swift +// DLSDK +// +// Created by osell on 2023/4/14. +// + +import UIKit +import Kingfisher +import CoreMedia + +public protocol ImageSource { + /// 图片资源URL + var imageURL: URL? { get } + /// 图片资源字符串 + var imageStr: String? { get } +} + +extension ImageSource { + var imageURL: URL? { nil } + + var imageStr: String? { nil } +} + +extension String: ImageSource { + public var imageURL: URL? { URL(string: self.urlEncodingWithQueryAllowedCharacters) } + + public var imageStr: String? { self } + +} + +extension URL: ImageSource { + public var imageURL: URL? { self } + + public var imageStr: String? { self.absoluteString.urlDecoded } +} + + +// MARK: - UIImageView +extension DLWrapper where Base: UIImageView { + + /// 设置图片 + /// - Parameters: + /// - url: 图片链接/名称, URL or String + /// - placeholder: 可选,默认nil + /// - completionHandler: 可选,默认为nil + @MainActor public func setImage(with url: ImageSource?, + placeholder: UIImage? = nil, + completionHandler: ((UIImage?, Error?) -> Void)? = nil) { + + guard let imageURL = url?.imageURL else { + let imageStr = url?.imageStr ?? "" + // 如果是本地图片,加载本地图片 + if let image = UIImage(named: imageStr) { + base.image = image + return + } + // 如果是SDK中图片,则加载SDK中图片 + if let image = UIImage(named: imageStr) { + base.image = image + return + } + // 都不存在,则置为nil + base.image = placeholder + return + } + + // 如果是视频, 获取视频第一帧 + if imageURL.imageStr?.contains(".mp4") == true { + let source = AVAssetImageDataProvider(assetURL: imageURL, time: CMTimeMakeWithSeconds(0.0, preferredTimescale: 1)) + base.kf.setImage(with: source.convertToSource(), placeholder: placeholder) { result in + switch result { + case let .success(imageinfo): + completionHandler?(imageinfo.image, nil) + case let .failure(error): + completionHandler?(nil, error) + } + } + } else { + // 使用kf加载图片 + base.kf.setImage(with: imageURL, placeholder: placeholder) { result in + switch result { + case let .success(imageinfo): + completionHandler?(imageinfo.image, nil) + case let .failure(error): + completionHandler?(nil, error) + } + } + } + + } +} + +// MARK: - Button +extension DLWrapper where Base: UIButton { + /// 设置按钮图片 + /// - Parameters: + /// - url: 图片链接, URL or String + /// - placeholder: 可选,默认nil + /// - completionHandler: 可选,默认为nil + @MainActor public func setImage(with url: ImageSource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + completionHandler: ((UIImage?, Error?) -> Void)? = nil) { + + guard let imageURL = url?.imageURL else { + let imageStr = url?.imageStr ?? "" + // 如果是本地图片,加载本地图片 + if let image = UIImage(named: imageStr) { + base.setImage(image, for: state) + return + } + // 如果是SDK中图片,则加载SDK中图片 + if let image = UIImage(named: imageStr) { + base.setImage(image, for: state) + return + } + // 都不存在,则置为nil + base.setImage(placeholder, for: state) + return + } + // 使用kf加载图片 + base.kf.setImage(with: imageURL, for: state, placeholder: placeholder, completionHandler: { result in + switch result { + case let .success(imageinfo): + completionHandler?(imageinfo.image, nil) + case let .failure(error): + completionHandler?(nil, error) + } + }) + } + + /// 设置按钮背景图片 + /// - Parameters: + /// - url: 图片链接, URL or String + /// - placeholder: 可选,默认nil + /// - completionHandler: 可选,默认为nil + @MainActor public func setBackgroundImage(with url: ImageSource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + completionHandler: ((UIImage?, Error?) -> Void)? = nil) { + + guard let imageURL = url?.imageURL else { + let imageStr = url?.imageStr ?? "" + // 如果是本地图片,加载本地图片 + if let image = UIImage(named: imageStr) { + base.setBackgroundImage(image, for: state) + return + } + // 如果是SDK中图片,则加载SDK中图片 + if let image = UIImage(named: imageStr) { + base.setBackgroundImage(image, for: state) + return + } + // 都不存在,则置为nil + base.setBackgroundImage(placeholder, for: state) + return + } + // 使用kf加载图片 + base.kf.setBackgroundImage(with: imageURL, for: state, placeholder: placeholder, completionHandler: { result in + switch result { + case let .success(imageinfo): + completionHandler?(imageinfo.image, nil) + case let .failure(error): + completionHandler?(nil, error) + } + }) + } +} diff --git a/QuickLocation/Plugin/NotEmpty.swift b/QuickLocation/Plugin/NotEmpty.swift new file mode 100644 index 00000000..7df9e773 --- /dev/null +++ b/QuickLocation/Plugin/NotEmpty.swift @@ -0,0 +1,50 @@ +// +// NotEmpty.swift +// DLSDK +// +// Created by osell on 2023/11/17. +// + +import Foundation +import Moya + +public protocol NotEmptyProtocol { + /// 是否不为空 + var isNotEmpty: Bool { get } +} + +public extension NotEmptyProtocol { + var isNotEmpty: Bool { true } +} + +/// 判断是否不为空 +/// - Parameter objcet: T必须遵守NotEmptyProtocol +/// - Returns: 布尔值,true不为空,false为空 +@discardableResult +public func NotEmpty(_ objcet: T?) -> Bool { + objcet?.isNotEmpty ?? false +} + + +extension String: NotEmptyProtocol { + public var isNotEmpty: Bool { trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false } +} + +extension Array: NotEmptyProtocol { + public var isNotEmpty: Bool { count > 0 } +} + +extension Dictionary: NotEmptyProtocol { + public var isNotEmpty: Bool { count > 0 } +} + +extension Set: NotEmptyProtocol { + public var isNotEmpty: Bool { count > 0 } +} + +extension NSObject: NotEmptyProtocol {} +extension Int: NotEmptyProtocol {} +extension Float: NotEmptyProtocol {} +extension Double: NotEmptyProtocol {} +extension CGFloat: NotEmptyProtocol {} +extension Response: NotEmptyProtocol {} diff --git a/QuickLocation/QuickLocation-Bridging-Header.h b/QuickLocation/QuickLocation-Bridging-Header.h new file mode 100644 index 00000000..cf7afbdd --- /dev/null +++ b/QuickLocation/QuickLocation-Bridging-Header.h @@ -0,0 +1,32 @@ +// +// QuickLocation-Bridging-Header.h +// QuickLocation +// + +#ifndef QuickLocation_Bridging_Header_h +#define QuickLocation_Bridging_Header_h + +#import + +// Core Extensions +#import "UINavigationController+FDFullscreenPopGesture.h" +#import "UIButton+RTL.h" + +// MXParallaxHeader +#import "MXParallaxHeader.h" +#import "MXScrollView.h" +#import "MXScrollViewController.h" + +// Pop +#import "DLViewTransition.h" + +// TTGTagCollectionView +#import "TTGTagCollectionView.h" +#import "TTGTextTagCollectionView.h" +#import "TTGTextTag.h" +#import "TTGTextTagContent.h" +#import "TTGTextTagStringContent.h" +#import "TTGTextTagAttributedStringContent.h" +#import "TTGTextTagStyle.h" + +#endif /* QuickLocation_Bridging_Header_h */ diff --git a/QuickLocation/Resource/Font/D-DIN-PRO-500-Medium.otf b/QuickLocation/Resource/Font/D-DIN-PRO-500-Medium.otf new file mode 100644 index 00000000..d72d454e Binary files /dev/null and b/QuickLocation/Resource/Font/D-DIN-PRO-500-Medium.otf differ diff --git a/QuickLocation/Resource/Font/YouSheBiaoTiHei.ttf b/QuickLocation/Resource/Font/YouSheBiaoTiHei.ttf new file mode 100644 index 00000000..3729151a Binary files /dev/null and b/QuickLocation/Resource/Font/YouSheBiaoTiHei.ttf differ diff --git a/QuickLocation/Resource/Font/douyu.otf b/QuickLocation/Resource/Font/douyu.otf new file mode 100644 index 00000000..3d9732ce Binary files /dev/null and b/QuickLocation/Resource/Font/douyu.otf differ diff --git a/QuickLocation/Resource/Font/pmzd.ttf b/QuickLocation/Resource/Font/pmzd.ttf new file mode 100644 index 00000000..0118a4bd Binary files /dev/null and b/QuickLocation/Resource/Font/pmzd.ttf differ diff --git a/QuickLocation/Resource/Font/zihunbiantaoti-r.ttf b/QuickLocation/Resource/Font/zihunbiantaoti-r.ttf new file mode 100644 index 00000000..06d8251b Binary files /dev/null and b/QuickLocation/Resource/Font/zihunbiantaoti-r.ttf differ diff --git a/QuickLocation/RxSwift/Action+Internal.swift b/QuickLocation/RxSwift/Action+Internal.swift new file mode 100644 index 00000000..4b80b3ec --- /dev/null +++ b/QuickLocation/RxSwift/Action+Internal.swift @@ -0,0 +1,36 @@ +import Foundation +import RxSwift + +public struct AssociatedKeys { + public static var Action = "rx_action" + public static var DisposeBag = "rx_disposeBag" +} + +// Note: Actions performed in this extension are _not_ locked +// So be careful! +extension NSObject { + + // A dispose bag to be used exclusively for the instance's rx.action. + public var actionDisposeBag: DisposeBag { + var disposeBag: DisposeBag + + if let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag { + disposeBag = lookup + } else { + disposeBag = DisposeBag() + objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, disposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + return disposeBag + } + + // Resets the actionDisposeBag to nil, disposeing of any subscriptions within it. + public func resetActionDisposeBag() { + objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + // Uses objc_sync on self to perform a locked operation. + public func doLocked(_ closure: () -> Void) { + objc_sync_enter(self); defer { objc_sync_exit(self) } + closure() + } +} diff --git a/QuickLocation/RxSwift/Action.swift b/QuickLocation/RxSwift/Action.swift new file mode 100644 index 00000000..56ccc30b --- /dev/null +++ b/QuickLocation/RxSwift/Action.swift @@ -0,0 +1,137 @@ +import Foundation +import RxSwift +import RxCocoa + +/// Typealias for compatibility with UIButton's rx.action property. +public typealias CocoaAction = Action +/// Typealias for actions with work factory returns `Completable`. +public typealias CompletableAction = Action + +/// Possible errors from invoking execute() +public enum ActionError: Error { + case notEnabled + case underlyingError(Error) +} + +/** +Represents a value that accepts a workFactory which takes some Observable as its input +and produces an Observable as its output. + +When this excuted via execute() or inputs subject, it passes its parameter to this closure and subscribes to the work. +*/ +public final class Action { + public typealias WorkFactory = (Input) -> Observable + + public let _enabledIf: Observable + public let workFactory: WorkFactory + + /// Inputs that triggers execution of action. + /// This subject also includes inputs as aguments of execute(). + /// All inputs are always appear in this subject even if the action is not enabled. + /// Thus, inputs count equals elements count + errors count. + public let inputs = InputSubject() + + /// Errors aggrevated from invocations of execute(). + /// Delivered on whatever scheduler they were sent from. + public let errors: Observable + + /// Whether or not we're currently executing. + /// Delivered on whatever scheduler they were sent from. + public let elements: Observable + + /// Whether or not we're currently executing. + public let executing: Observable + + /// Observables returned by the workFactory. + /// Useful for sending results back from work being completed + /// e.g. response from a network call. + public let executionObservables: Observable> + + /// Whether or not we're enabled. Note that this is a *computed* sequence + /// property based on enabledIf initializer and if we're currently executing. + /// Always observed on MainScheduler. + public let enabled: Observable + + private let disposeBag = DisposeBag() + + public convenience init( + enabledIf: Observable = Observable.just(true), + workFactory: @escaping (Input) -> O + ) where O.Element == Element { + self.init(enabledIf: enabledIf) { + workFactory($0).asObservable() + } + } + + public init( + enabledIf: Observable = Observable.just(true), + workFactory: @escaping WorkFactory) { + + self._enabledIf = enabledIf + self.workFactory = workFactory + + let enabledSubject = BehaviorSubject(value: false) + enabled = enabledSubject.asObservable() + + let errorsSubject = PublishSubject() + errors = errorsSubject.asObservable() + + executionObservables = inputs + .withLatestFrom(enabled) { input, enabled in (input, enabled) } + .flatMap { input, enabled -> Observable> in + if enabled { + return Observable.of(workFactory(input) + .do(onError: { errorsSubject.onNext(.underlyingError($0)) }) + .share(replay: 1, scope: .forever)) + } else { + errorsSubject.onNext(.notEnabled) + return Observable.empty() + } + } + .share() + + elements = executionObservables + .flatMap { $0.catch { _ in Observable.empty() } } + + executing = executionObservables.flatMap { + execution -> Observable in + let execution = execution + .flatMap { _ in Observable.empty() } + .catch { _ in Observable.empty() } + + return Observable.concat([Observable.just(true), + execution, + Observable.just(false)]) + } + .startWith(false) + .share(replay: 1, scope: .forever) + + Observable + .combineLatest(executing, enabledIf) { !$0 && $1 } + .bind(to: enabledSubject) + .disposed(by: disposeBag) + } + + @discardableResult + public func execute(_ value: Input) -> Observable { + defer { + inputs.onNext(value) + } + + let subject = ReplaySubject.createUnbounded() + + let work = executionObservables + .map { $0.catch { throw ActionError.underlyingError($0) } } + + let error = errors + .map { Observable.error($0) } + + work.amb(error) + .take(1) + .flatMap { $0 } + .subscribe(subject) + .disposed(by: disposeBag) + + return subject.asObservable() + } +} diff --git a/QuickLocation/RxSwift/Button+Action.swift b/QuickLocation/RxSwift/Button+Action.swift new file mode 100644 index 00000000..265bd89b --- /dev/null +++ b/QuickLocation/RxSwift/Button+Action.swift @@ -0,0 +1,89 @@ +#if os(iOS) || os(tvOS) || os(macOS) +import Foundation +#if os(iOS) || os(tvOS) + import UIKit + public typealias Button = UIKit.UIButton +#elseif os(macOS) + import Cocoa + public typealias Button = Cocoa.NSButton +#endif +import RxSwift +import RxCocoa + +public extension Reactive where Base: Button { + /// Binds enabled state of action to button, and subscribes to rx_tap to execute action. + /// These subscriptions are managed in a private, inaccessible dispose bag. To cancel + /// them, set the rx.action to nil or another action. + var action: CocoaAction? { + get { + var action: CocoaAction? + action = objc_getAssociatedObject(self.base, &AssociatedKeys.Action) as? Action + return action + } + + set { + // Store new value. + objc_setAssociatedObject(self.base, &AssociatedKeys.Action, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + + // This effectively disposes of any existing subscriptions. + self.base.resetActionDisposeBag() + + // Set up new bindings, if applicable. + if let action = newValue { + action + .enabled + .bind(to: self.isEnabled) + .disposed(by: self.base.actionDisposeBag) + + // Technically, this file is only included on tv/iOS platforms, + // so this optional will never be nil. But let's be safe 😉 + let lookupControlEvent: ControlEvent? + + #if os(tvOS) + lookupControlEvent = self.primaryAction + #elseif os(iOS) || os(macOS) + lookupControlEvent = self.tap + #endif + + guard let controlEvent = lookupControlEvent else { + return + } + + controlEvent + .bind(to: action.inputs) + .disposed(by: self.base.actionDisposeBag) + } + } + } + + /// Binds enabled state of action to button, and subscribes to rx_tap to execute action with given input transform. + /// These subscriptions are managed in a private, inaccessible dispose bag. To cancel + /// them, call bindToAction with another action or call unbindAction(). + func bind(to action: Action, inputTransform: @escaping (Base) -> (Input)) { + // This effectively disposes of any existing subscriptions. + unbindAction() + + // Technically, this file is only included on tv/iOS platforms, + // so this optional will never be nil. But let's be safe 😉 + let lookupControlEvent: ControlEvent? + + #if os(tvOS) + lookupControlEvent = self.primaryAction + #elseif os(iOS) || os(macOS) + lookupControlEvent = self.tap + #endif + + guard let controlEvent = lookupControlEvent else { + return + } + self.bind(to: action, controlEvent: controlEvent, inputTransform: inputTransform) + } + + /// Binds enabled state of action to button, and subscribes to rx_tap to execute action with given input value. + /// These subscriptions are managed in a private, inaccessible dispose bag. To cancel + /// them, call bindToAction with another action or call unbindAction(). + func bind(to action: Action, input: Input) { + self.bind(to: action) { _ in input } + } +} +#endif diff --git a/QuickLocation/RxSwift/Control+Action.swift b/QuickLocation/RxSwift/Control+Action.swift new file mode 100644 index 00000000..a77cb0ad --- /dev/null +++ b/QuickLocation/RxSwift/Control+Action.swift @@ -0,0 +1,40 @@ +#if os(iOS) || os(tvOS) || os(macOS) +import Foundation +#if os(iOS) || os(tvOS) + import UIKit + public typealias Control = UIKit.UIControl +#elseif os(macOS) + import Cocoa + public typealias Control = Cocoa.NSControl +#endif +import RxSwift +import RxCocoa + +public extension Reactive where Base: Control { + /// Binds enabled state of action to control, and subscribes action's execution to provided controlEvents. + /// These subscriptions are managed in a private, inaccessible dispose bag. To cancel + /// them, set the rx.action to nil or another action, or call unbindAction(). + func bind(to action: Action, controlEvent: ControlEvent, inputTransform: @escaping (Base) -> (Input)) { + // This effectively disposes of any existing subscriptions. + unbindAction() + + // For each tap event, use the inputTransform closure to provide an Input value to the action + controlEvent + .map { inputTransform(self.base) } + .bind(to: action.inputs) + .disposed(by: self.base.actionDisposeBag) + + // Bind the enabled state of the control to the enabled state of the action + action + .enabled + .bind(to: self.isEnabled) + .disposed(by: self.base.actionDisposeBag) + } + + /// Unbinds any existing action, disposing of all subscriptions. + func unbindAction() { + self.base.resetActionDisposeBag() + } +} +#endif + diff --git a/QuickLocation/RxSwift/InputSubject.swift b/QuickLocation/RxSwift/InputSubject.swift new file mode 100644 index 00000000..cd163e46 --- /dev/null +++ b/QuickLocation/RxSwift/InputSubject.swift @@ -0,0 +1,93 @@ +import Foundation +import RxSwift + +/// A special subject for Action.inputs. It only emits `.next` event. +public class InputSubject: ObservableType, Cancelable, SubjectType, ObserverType { + + public typealias E = Element + typealias Key = UInt + + /// Indicates whether the subject has any observers + public var hasObservers: Bool { + _lock.lock() + let count = _observers.count > 0 + _lock.unlock() + return count + } + + // state + private let _lock = NSRecursiveLock() + private var _nextKey: Key = 0 + private var _observers: [Key: (Event) -> ()] = [:] + private var _isDisposed = false + + /// Indicates whether the subject has been isDisposed. + public var isDisposed: Bool { + _lock.lock() + let isDisposed = _isDisposed + _lock.unlock() + return isDisposed + } + + /// Creates a subject. + public init() { + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + /// Notifies all subscribed observers abount only `.next` event. + /// + /// - parameter event: Event to send to the observers. + public func on(_ event: Event) { + _lock.lock() + switch event { + case .next(_) where !_isDisposed: + _observers.values.forEach { $0(event) } + default: + break + } + _lock.unlock() + } + + /** + Subscribes an observer to the subject. + + - parameter observer: Observer to subscribe to the subject. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func subscribe(_ observer: O) -> Disposable where O.Element == Element { + _lock.lock() + + if _isDisposed { + observer.on(.error(RxError.disposed(object: self))) + return Disposables.create() + } + + let key = _nextKey + _nextKey += 1 + _observers[key] = observer.on + _lock.unlock() + + return Disposables.create { [weak self] in + self?._lock.lock() + self?._observers.removeValue(forKey: key) + self?._lock.unlock() + } + } + + /// Unsubscribe all observers and release resources. + public func dispose() { + _lock.lock() + _isDisposed = true + _observers.removeAll() + _lock.unlock() + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif + +} diff --git a/QuickLocation/RxSwift/NSObject+Rx.swift b/QuickLocation/RxSwift/NSObject+Rx.swift new file mode 100644 index 00000000..afe5fd05 --- /dev/null +++ b/QuickLocation/RxSwift/NSObject+Rx.swift @@ -0,0 +1,49 @@ +import Foundation +import RxSwift +import ObjectiveC +import RxCocoa + +fileprivate var disposeBagContext: UInt8 = 0 + +public extension Reactive where Base: AnyObject { + func synchronizedBag( _ action: () -> T) -> T { + objc_sync_enter(self.base) + let result = action() + objc_sync_exit(self.base) + return result + } +} + +public extension Reactive where Base: AnyObject { + + /// a unique DisposeBag that is related to the Reactive.Base instance only for Reference type + var disposeBag: DisposeBag { + get { + return synchronizedBag { + if let disposeObject = objc_getAssociatedObject(base, &disposeBagContext) as? DisposeBag { + return disposeObject + } + let disposeObject = DisposeBag() + objc_setAssociatedObject(base, &disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return disposeObject + } + } + + set { + synchronizedBag { + objc_setAssociatedObject(base, &disposeBagContext, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + } +} + +public extension Reactive where Base: UIView { + + var tapGesture: ControlEvent { + let tap = UITapGestureRecognizer() + base.isUserInteractionEnabled = true + base.addGestureRecognizer(tap) + return tap.rx.event + } + +} diff --git a/QuickLocation/RxSwift/ObservableType+ObjectMapper.swift b/QuickLocation/RxSwift/ObservableType+ObjectMapper.swift new file mode 100755 index 00000000..3ab3d75f --- /dev/null +++ b/QuickLocation/RxSwift/ObservableType+ObjectMapper.swift @@ -0,0 +1,91 @@ +// +// ObserverType+ObjectMapper.swift +// +// Created by Ivan Bruel on 09/12/15. +// Copyright © 2015 Ivan Bruel. All rights reserved. +// + +import Foundation +import Moya +import ObjectMapper +import RxSwift + +/// Extension for processing Responses into Mappable objects through ObjectMapper +public extension ObservableType where Element == Response { + + /// Maps data received from the signal into an object + /// which implements the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, context: MapContext? = nil) -> Observable { + return flatMap { response -> Observable in + Observable.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, context: MapContext? = nil) -> Observable<[T]> { + return flatMap { response -> Observable<[T]> in + Observable.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an object + /// which implements the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable { + return flatMap { response -> Observable in + Observable.just(try response.map(T.self, atKeyPath: keyPath, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<[T]> { + return flatMap { response -> Observable<[T]> in + Observable.just(try response.map(type, atKeyPath: keyPath, context: context)) + } + } +} + +// MARK: - ImmutableMappable +public extension ObservableType where Element == Response { + + /// Maps data received from the signal into an object + /// which implements the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, context: MapContext? = nil) -> Observable { + return flatMap { response -> Observable in + Observable.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, context: MapContext? = nil) -> Observable<[T]> { + return flatMap { response -> Observable<[T]> in + Observable.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an object + /// which implements the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable { + return flatMap { response -> Observable in + Observable.just(try response.map(T.self, atKeyPath: keyPath, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<[T]> { + return flatMap { response -> Observable<[T]> in + Observable.just(try response.map(type, atKeyPath: keyPath, context: context)) + } + } +} diff --git a/QuickLocation/RxSwift/Single+ObjectMapper.swift b/QuickLocation/RxSwift/Single+ObjectMapper.swift new file mode 100755 index 00000000..97cf2aee --- /dev/null +++ b/QuickLocation/RxSwift/Single+ObjectMapper.swift @@ -0,0 +1,91 @@ +// +// Single+MoyaObjectMapper.swift +// +// Created by Ivan Bruel on 09/12/15. +// Copyright © 2015 Ivan Bruel. All rights reserved. +// + +import Foundation +import Moya +import ObjectMapper +import RxSwift + +/// Extension for processing Responses into Mappable objects through ObjectMapper +public extension PrimitiveSequence where Trait == SingleTrait, Element == Response { + + /// Maps data received from the signal into an object + /// which implements the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, context: MapContext? = nil) -> Single { + return flatMap { response -> Single in + Single.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, context: MapContext? = nil) -> Single<[T]> { + return flatMap { response -> Single<[T]> in + Single.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an object + /// which implements the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Single { + return flatMap { response -> Single in + Single.just(try response.map(type, atKeyPath: keyPath, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the Mappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Single<[T]> { + return flatMap { response -> Single<[T]> in + Single.just(try response.map(type, atKeyPath: keyPath, context: context)) + } + } +} + +// MARK: - ImmutableMappable +public extension PrimitiveSequence where Trait == SingleTrait, Element == Response { + + /// Maps data received from the signal into an object + /// which implements the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, context: MapContext? = nil) -> Single { + return flatMap { response -> Single in + Single.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, context: MapContext? = nil) -> Single<[T]> { + return flatMap { response -> Single<[T]> in + Single.just(try response.map(type, context: context)) + } + } + + /// Maps data received from the signal into an object + /// which implements the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Single { + return flatMap { response -> Single in + Single.just(try response.map(type, atKeyPath: keyPath, context: context)) + } + } + + /// Maps data received from the signal into an array of objects + /// which implement the ImmutableMappable protocol and returns the result back + /// If the conversion fails, the signal errors. + func map(_ type: [T].Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Single<[T]> { + return flatMap { response -> Single<[T]> in + Single.just(try response.map(type, atKeyPath: keyPath, context: context)) + } + } +} diff --git a/QuickLocation/Section/Home/HomeView.swift b/QuickLocation/Section/Home/HomeView.swift new file mode 100644 index 00000000..df59676b --- /dev/null +++ b/QuickLocation/Section/Home/HomeView.swift @@ -0,0 +1,355 @@ +// +// HomeView.swift +// QuickLocation +// +// Created by 八条 on 2026/5/27. +// + +import UIKit +import RxSwift +import RxCocoa +#if !targetEnvironment(simulator) +import MAMapKit +#endif + +class HomeView: UIView { + + var disposeBag = DisposeBag() + + // MARK: - Map + #if !targetEnvironment(simulator) + lazy var mapView: MAMapView = { + let mv = MAMapView() + mv.zoomLevel = 15 + mv.minZoomLevel = 3 + mv.maxZoomLevel = 20 + mv.showsUserLocation = true + mv.userTrackingMode = .follow + mv.showsCompass = false + mv.showsScale = false + mv.isRotateEnabled = false + mv.isRotateCameraEnabled = false + return mv + }() + #else + lazy var mapPlaceholderView: UIView = { + let v = UIView() + v.backgroundColor = UIColor(hexStr: "#EDEDED") + let label = UILabel() + label.text = "Map requires a real device" + label.font = UIFont.systemFont(ofSize: 14) + label.textColor = UIColor(hexStr: "#999999") + label.textAlignment = .center + v.addSubview(label) + label.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + label.centerXAnchor.constraint(equalTo: v.centerXAnchor), + label.centerYAnchor.constraint(equalTo: v.centerYAnchor) + ]) + return v + }() + #endif + + // MARK: - Setup + private func setupRx() { + + } + + private func setupUI() { + #if !targetEnvironment(simulator) + addSubview(mapView) + #else + addSubview(mapPlaceholderView) + #endif + + addSubview(navBarBg) + addSubview(avatarImgView) + addSubview(groupView) + groupView.addSubview(groupIconView) + groupView.addSubview(groupNameLab) + groupView.addSubview(groupArrowIconView) + addSubview(toolsView) + addSubview(locationView) + locationView.addSubview(locationIconView) + + #if !targetEnvironment(simulator) + mapView.layoutChain + .top() + .edges(excludingEdge: .top) + sendSubviewToBack(mapView) + #else + mapPlaceholderView.layoutChain + .topToBottomOfView(navBarBg) + .left(0).right(0).bottom(0) + #endif + + navBarBg.layoutChain + .edges(excludingEdge: .bottom) + .heightToWidth(160/375) + + avatarImgView.layoutChain + .top(59) + .left(15) + .width(36) + .heightToWidth(1) + + groupView.layoutChain + .centerY(avatarImgView) + .height(36) + .centerX() + .width(185, relation: .greaterThanOrEqual) + + groupIconView.layoutChain + .left(11) + .centerY() + .width(30) + .height(30) + + groupArrowIconView.layoutChain + .right(15) + .centerY() + .width(15) + .height(8.5) + + groupNameLab.layoutChain + .edgesVertical() + .leftToRightOfView(groupIconView) + .rightToLeftOfView(groupArrowIconView) + + toolsView.layoutChain + .left(23) + .centerY() + .width(40) + + bubbleView.layoutChain + .top(12) + .height(58) + + bubbleIcon.layoutChain + .top() + .centerX() + .width(28) + .height(28) + + bubbleLab.layoutChain + .topToBottomOfView(bubbleIcon, offset: 4) + .edgesHorzontal() + + signInView.layoutChain.height(58) + + signInIcon.layoutChain + .top() + .centerX() + .width(28) + .height(28) + + signInLab.layoutChain + .topToBottomOfView(signInIcon, offset: 4) + .edgesHorzontal() + + sosView.layoutChain + .height(56) + + sosIcon.layoutChain + .top() + .centerX() + .width(28) + .height(28) + + sosLab.layoutChain + .topToBottomOfView(sosIcon, offset: 4) + .edgesHorzontal() + + locationView.layoutChain + .right(15) + .bottomToView(toolsView) + .width(40) + .height(40) + + locationIconView.layoutChain + .centerX() + .centerY() + } + + override init(frame: CGRect) { + super.init(frame: .zero) + backgroundColor = .white + setupUI() + setupRx() + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - UI Components + lazy var navBarBg: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Home/navBar_bg") + view.contentMode = .scaleAspectFill + return view + }() + + lazy var avatarImgView: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "map_avatar_1") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + view.cornerRadius = 18 + return view + }() + + lazy var groupView: UIView = { + let view = UIView() + view.backgroundColor = .white + view.cornerRadius = 18 + return view + }() + + lazy var groupIconView: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Home/group") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + lazy var groupNameLab: UILabel = { + let label = UILabel() + label.text = "我的圈子" + label.font = .systemFont(ofSize: 16, weight: .medium) + label.textColor = UIColor(hexStr: "#0F2846") + label.textAlignment = .center + return label + }() + + lazy var groupArrowIconView: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Home/arrow_down") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + // MARK: - 侧边工具栏 + lazy var toolsView: UIStackView = { + let view = UIStackView(arrangedSubviews: [bubbleView, signInView, sosView]) + view.axis = .vertical + view.alignment = .center + view.spacing = 0 + view.backgroundColor = .black.withAlphaComponent(0.5) + view.cornerRadius = 20 + return view + }() + + // 气泡 + lazy var bubbleView: UIView = { + let view = UIView() + view.backgroundColor = .clear + view.addSubview(bubbleIcon) + view.addSubview(bubbleLab) + + let lineView = UIView() + lineView.backgroundColor = .white + view.addSubview(lineView) + lineView.layoutChain + .width(12) + .height(2) + .centerX() + .bottom(7) + + return view + }() + + lazy var bubbleIcon: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Home/bubble") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + lazy var bubbleLab: UILabel = { + let label = UILabel() + label.text = "气泡" + label.font = .systemFont(ofSize: 10, weight: .medium) + label.textColor = .white + label.textAlignment = .center + return label + }() + + // 签到 + lazy var signInView: UIView = { + let view = UIView() + view.backgroundColor = .clear + view.addSubview(signInIcon) + view.addSubview(signInLab) + let lineView = UIView() + lineView.backgroundColor = .white + view.addSubview(lineView) + lineView.layoutChain + .width(12) + .height(2) + .centerX() + .bottom(7) + return view + }() + + lazy var signInIcon: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Home/signIn") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + lazy var signInLab: UILabel = { + let label = UILabel() + label.text = "签到" + label.font = .systemFont(ofSize: 10, weight: .medium) + label.textColor = .white + label.textAlignment = .center + return label + }() + + // SOS + lazy var sosView: UIView = { + let view = UIView() + view.backgroundColor = .clear + view.addSubview(sosIcon) + view.addSubview(sosLab) + return view + }() + + lazy var sosIcon: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Home/sos") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + lazy var sosLab: UILabel = { + let label = UILabel() + label.text = "SOS" + label.font = .systemFont(ofSize: 10, weight: .medium) + label.textColor = .white + label.textAlignment = .center + return label + }() + + // MARK: - 定位按钮 + lazy var locationView: UIView = { + let view = UIView() + view.backgroundColor = .black.withAlphaComponent(0.4) + view.cornerRadius = 20 + return view + }() + + lazy var locationIconView: UIImageView = { + let view = UIImageView() + view.backgroundColor = .clear + view.image = UIImage(named: "Home/location") + return view + }() +} diff --git a/QuickLocation/Section/Home/HomeViewController.swift b/QuickLocation/Section/Home/HomeViewController.swift new file mode 100644 index 00000000..93ce1fac --- /dev/null +++ b/QuickLocation/Section/Home/HomeViewController.swift @@ -0,0 +1,171 @@ +// +// HomeViewController.swift +// QuickLocation +// +// Created by 八条 on 2026/5/27. +// + +import UIKit +import RxSwift +import CoreLocation +#if !targetEnvironment(simulator) +import MAMapKit +#endif + +class HomeViewController: BaseViewController { + + override var isNavigationBarHidden: Bool { true } + override var preferredStatusBarStyle: UIStatusBarStyle { .default } + + // MARK: - Properties + fileprivate var rootView: HomeView! + private let locationManager = CLLocationManager() + private var currentHeading: Double = 0 + private var members: [CircleMember] = [] + private var currentUserMember: CircleMember? + + override func loadView() { + #if !targetEnvironment(simulator) + MAMapView.updatePrivacyAgree(.didAgree) + MAMapView.updatePrivacyShow(.didShow, privacyInfo: .didContain) + #endif + + rootView = HomeView(frame: UIScreen.main.bounds) + view = rootView + } + + override func viewDidLoad() { + super.viewDidLoad() + setupMap() + setupLocation() + loadMembers() + } + + // MARK: - Map Setup + private func setupMap() { + #if !targetEnvironment(simulator) + rootView.mapView.delegate = self + + let r = MAUserLocationRepresentation() + r.showsAccuracyRing = false + r.showsHeadingIndicator = false + rootView.mapView.update(r) + #endif + } + + // MARK: - Location + private func setupLocation() { + locationManager.delegate = self + locationManager.desiredAccuracy = kCLLocationAccuracyBest + locationManager.requestWhenInUseAuthorization() + locationManager.startUpdatingHeading() + locationManager.startUpdatingLocation() + } + + // MARK: - Members + private func loadMembers() { + members = .mock + currentUserMember = members.first { $0.isCurrentUser } + updateAnnotations() + centerOnMembers() + } + + private func centerOnMembers() { + #if !targetEnvironment(simulator) + guard !members.isEmpty else { return } + if let current = currentUserMember { + rootView.mapView.setCenter(current.coordinate, animated: false) + } else if let first = members.first { + rootView.mapView.setCenter(first.coordinate, animated: false) + } + #endif + } + + // MARK: - Annotations + private func updateAnnotations() { + #if !targetEnvironment(simulator) + let mapView = rootView.mapView + let existing = mapView.annotations ?? [] + let existingMemberIDs = Set(existing.compactMap { ($0 as? MemberAnnotation)?.member.id }) + let newMemberIDs = Set(members.map { $0.id }) + + let toRemove = existing.filter { ann in + guard let ma = ann as? MemberAnnotation else { return false } + return !newMemberIDs.contains(ma.member.id) + } + mapView.removeAnnotations(toRemove) + + let toAdd = members.filter { !$0.isCurrentUser && !existingMemberIDs.contains($0.id) } + let annotations = toAdd.map { MemberAnnotation(member: $0) } + mapView.addAnnotations(annotations) + #endif + } + + // MARK: - Heading + private func updateCurrentUserHeading() { + #if !targetEnvironment(simulator) + guard let annotations = rootView.mapView.annotations else { return } + for ann in annotations { + guard ann is MAUserLocation else { continue } + if let view = rootView.mapView.view(for: ann as! MAAnnotation) as? MemberAnnotationView { + view.updateHeading(currentHeading) + } + break + } + #endif + } +} + +#if !targetEnvironment(simulator) +// MARK: - MAMapViewDelegate +extension HomeViewController: MAMapViewDelegate { + + func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! { + if annotation is MAUserLocation { + let identifier = "UserLocationAnnotation" + var view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MemberAnnotationView + if view == nil { + view = MemberAnnotationView(annotation: annotation, reuseIdentifier: identifier) + } + if let currentUser = currentUserMember { + view?.configure(with: currentUser) + } + return view + } + + guard let memberAnnotation = annotation as? MemberAnnotation else { return nil } + + let identifier = "MemberAnnotation" + var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MemberAnnotationView + if annotationView == nil { + annotationView = MemberAnnotationView(annotation: memberAnnotation, reuseIdentifier: identifier) + } else { + annotationView?.annotation = memberAnnotation + } + + annotationView?.configure(with: memberAnnotation.member) + return annotationView + } +} +#endif + +// MARK: - CLLocationManagerDelegate +extension HomeViewController: CLLocationManagerDelegate { + + func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { + let h = newHeading.trueHeading + guard h >= 0 else { return } + currentHeading = h + updateCurrentUserHeading() + } + + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + #if !targetEnvironment(simulator) + guard let location = locations.last else { return } + rootView.mapView.setCenter(location.coordinate, animated: true) + #endif + } + + func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { + } +} diff --git a/QuickLocation/Section/Launch/LaunchViewController.swift b/QuickLocation/Section/Launch/LaunchViewController.swift new file mode 100644 index 00000000..5b0cddfe --- /dev/null +++ b/QuickLocation/Section/Launch/LaunchViewController.swift @@ -0,0 +1,238 @@ +// +// LaunchViewController.swift +// SHECommunity +// +// Created by Lin on 2025/1/3. +// + +import UIKit +import RxSwift +import SwiftyUserDefaults +import RxCocoa + +class LaunchViewController: BaseViewController { + + private let guideImgList: [String] = [ + "guide_1", + "guide_2", + "guide_3", + "guide_4", + "guide_5" + ] + + private let showVersion = 1 + + override func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + view.backgroundColor = UIColor(hexStr: "#E0F2FF") + setupLayout() + + experienceBtn.rx.tap.subscribe(onNext: { _ in +// Defaults[\.guideShowVersion] = self.showVersion + AppDelegate.shared.showMainViewController() + }).disposed(by: disposeBag) + + getUserConfig() + + navigateAfterDelay() + } + + private func navigateAfterDelay() { + Observable.just(()) + .delay(.milliseconds(2500), scheduler: MainScheduler.instance) + .subscribe(onNext: { [weak self] in + self?.navigateToNext() + }) + .disposed(by: disposeBag) + } + + private func navigateToNext() { + let hasShownGuide = UserDefaults.standard.bool(forKey: "hasShownGuide") + if hasShownGuide { + let loginVC = LoginViewController() + UIView.transition(with: view.window!, duration: 0.4, options: .transitionCrossDissolve) { + self.view.window?.rootViewController = UINavigationController(rootViewController: loginVC) + } + } else { + collectionView.isHidden = false + pageControl.isHidden = false + experienceBtn.isHidden = false + } + } + + /// 获取用户配置 + func getUserConfig() { + SystemService.userConfig().subscribe(onNext: { response in + guard let model = response.model else { return } + // 保存用户数据 + AppContextManager.shared.saveAccount(model) + }, onError: { [weak self] (error) in + DLAlert.show(title: error.localizedDescription, + defaultTitle: "重试") { [weak self] in + guard let this = self else { return } + this.getUserConfig() + } + }).disposed(by: disposeBag) + } + + // MARK: - Init + init() { + super.init(nibName: nil, bundle: nil) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + lazy var launchLogoView: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Launch/logo") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + lazy var tipsImgView: UIImageView = { + let view = UIImageView() + view.image = UIImage(named: "Launch/slogan") + view.backgroundColor = .clear + view.contentMode = .scaleAspectFill + return view + }() + + /// 引导页 + lazy var collectionView: UICollectionView = { + let viewFlowLayout = UICollectionViewFlowLayout() + viewFlowLayout.scrollDirection = .horizontal + viewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) + viewFlowLayout.minimumLineSpacing = 0 + viewFlowLayout.minimumInteritemSpacing = 0 + viewFlowLayout.itemSize = CGSizeMake(kScreenWidth, kScreenHeight) + + let collectionView = UICollectionView(frame: .zero, collectionViewLayout: viewFlowLayout) + collectionView.backgroundColor = .white + collectionView.dataSource = self + collectionView.delegate = self + collectionView.showsVerticalScrollIndicator = false + collectionView.showsHorizontalScrollIndicator = false + collectionView.isPagingEnabled = true + collectionView.bounces = false + collectionView.register(GuideCell.self) + collectionView.isHidden = true + return collectionView + }() + + lazy var experienceBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setTitle("立即体验", for: .normal) + btn.setTitleColor(UIColor(hexStr: "#0F2846"), for: .normal) + btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + btn.setBackgroundImage(UIImage(named: "Guide/experience"), for: .normal) + btn.isHidden = true + return btn + }() + + lazy var pageControl: JJPageControl = { + let pageControl = JJPageControl(frame: CGRectMake(0, 0, kScreenWidth, 10)) + pageControl.currentColor = ThemeManager.shared.color.mainColor + pageControl.currentPointSize = CGSize(width: 20, height: 6) + pageControl.otherColor = ThemeManager.shared.color.mainColor.withAlphaComponent(0.5) + pageControl.otherPointSize = CGSize(width: 6, height: 6) + pageControl.pointCornerRadius = 3 + pageControl.controlSpacing = 18 + pageControl.pageAliment = .Center + pageControl.backgroundColor = .clear + pageControl.numberOfPages = guideImgList.count + pageControl.isHidden = true + return pageControl + }() +} + +extension LaunchViewController { + private func setupLayout() { + view.addSubview(launchLogoView) + view.addSubview(tipsImgView) + view.addSubview(collectionView) + view.addSubview(experienceBtn) + view.addSubview(pageControl) + + launchLogoView.layoutChain + .centerX() + .centerY() + + tipsImgView.layoutChain + .centerX() + .bottom(kSafeBottomMargin + 50) + + collectionView.layoutChain.edges() + + experienceBtn.layoutChain + .bottom(kSafeBottomMargin + 23) + .width(245) + .height(50) + .centerX() + + pageControl.layoutChain + .bottomToTopOfView(experienceBtn, offset: -25) + .edgesHorzontal(10) + .centerX() + .height(10) + } +} + +// MARK: - UICollectionViewDataSource +extension LaunchViewController: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + guideImgList.count + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell: GuideCell = collectionView.dequeueReusableCell(for: indexPath) + cell.configure(imageName: guideImgList[indexPath.row]) + return cell + } +} + +// MARK: - UICollectionViewDelegate +extension LaunchViewController: UICollectionViewDelegate { + func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { + if scrollView == collectionView { + let page = Int(scrollView.contentOffset.x / scrollView.dl.width) + pageControl.currentPage = page + } + } +} + +class GuideCell: UICollectionViewCell { + + func configure(imageName: String) { + imgView.image = UIImage(named: "Guide/" + imageName) + } + + private func setupSubViews() { + addSubview(imgView) + setupLayout() + } + + private func setupLayout() { + imgView.layoutChain.edges() + } + + lazy var imgView: UIImageView = { + let icon = UIImageView() + icon.contentMode = .scaleAspectFill + return icon + }() + + override init(frame: CGRect) { + super.init(frame: frame) + contentView.backgroundColor = .clear + setupSubViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/QuickLocation/Section/Login/LoginView.swift b/QuickLocation/Section/Login/LoginView.swift new file mode 100644 index 00000000..517203bd --- /dev/null +++ b/QuickLocation/Section/Login/LoginView.swift @@ -0,0 +1,416 @@ +// +// LoginView.swift +// QuickLocation +// +// Created by 八条 on 2026/5/26. +// + +import UIKit +import RxSwift +import RxCocoa +#if !targetEnvironment(simulator) +import GeYanSdk +#endif + +class LoginView: UIView { + + var disposeBag = DisposeBag() + var oneTapLogin = true + + private func setupRx() { + backBtn.rx.tap.subscribe(onNext: { _ in + AppRouter.shared.popOrDismiss() + }).disposed(by: disposeBag) + + phoneInputTF.rx.text + .map { text -> String? in + guard let text = text else { return nil } + return String(text.prefix(11)) + }.bind(to: phoneInputTF.rx.text) + .disposed(by: disposeBag) + + phoneInputTF.rx.text.orEmpty.map { phone -> Bool in + if phone.count == 11 { + return true + } else { + return false + } + } + .bind(to: smsCodeBtn.rx.isEnabled) + .disposed(by: disposeBag) + +// phoneLoginBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in +// guard let self = self else { return } +// self.oneTapLogin = !self.oneTapLogin +// self.otherPhoneView.isHidden = self.oneTapLogin +// self.loginButton.setTitle(self.oneTapLogin ? "本机号码一键登录" : "立即登录", for: .normal) +// self.phoneNumberLabel.isHidden = !self.oneTapLogin +// self.carrierLabel.isHidden = !self.oneTapLogin +// if self.oneTapLogin, let model = GyContentModel.current() { +// self.setupAgreementTextWithCarrier(carrier: model.term) +// } +// else { +// self.setupAgreementTextWithCarrier(carrier: "") +// } +// }.disposed(by: disposeBag) + } + + func setupAgreementTextWithCarrier(carrier: String) { + let text = carrier.isEmpty ? "登录即同意《隐私政策》和《用户协议》" : "登录即同意\(carrier)、《隐私政策》和《用户协议》" + agreementLabel.text = text + // 创建段落样式 + let paragraphStyle = NSMutableParagraphStyle() + // 设置行距(lineSpacing 是行间距,lineHeightMultiple 是行高倍数) + paragraphStyle.lineSpacing = 4.0 // 行间距 + + let attributedString = NSMutableAttributedString(string: text) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#A4A7AE"), + .paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: text.length)) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#16B3FF"), + .link: "Carrier"], + range: (text as NSString).range(of: carrier)) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#16B3FF"), + .link: "UserAgreement"], + range: (text as NSString).range(of: "《用户协议》")) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#16B3FF"), + .link: "PrivacyPolicy"], + range: (text as NSString).range(of: "《隐私政策》")) + + agreementTV.attributedText = attributedString + } + + private func setupUI() { + addSubview(bgMaskImage) + addSubview(backBtn) + addSubview(guestLoginButton) + addSubview(welcomeLabel) + addSubview(phoneNumberLabel) + addSubview(carrierLabel) + addSubview(otherPhoneView) + otherPhoneView.addSubview(phoneInputView) + otherPhoneView.addSubview(smsCodeInputView) + addSubview(loginButton) + addSubview(appleLoginBtn) + addSubview(wechatLoginBtn) + addSubview(phoneLoginBtn) + + addSubview(agreementView) + agreementView.addSubview(checkBox) + agreementView.addSubview(agreementTV) + agreementView.addSubview(agreementLabel) + + bgMaskImage.layoutChain.edges() + + backBtn.layoutChain + .top(54) + .left(15) + .width(24) + .height(24) + + guestLoginButton.layoutChain + .centerY(backBtn) + .right(15) + .width(85) + .height(29) + + welcomeLabel.layoutChain + .top(202 - kNaviHeight) + .centerX() + .edgesHorzontal() + + phoneNumberLabel.layoutChain + .topToBottomOfView(welcomeLabel, offset: 78) + .centerX() + + carrierLabel.layoutChain + .topToBottomOfView(phoneNumberLabel, offset: 4) + .centerX() + + otherPhoneView.layoutChain + .topToBottomOfView(welcomeLabel, offset: 43) + .centerX() + + phoneInputView.layoutChain + .edges(excludingEdge: .bottom) + .width(259) + .height(50) + + phoneLineView.layoutChain + .left(58) + .centerY() + .width(1) + .height(25) + + areaCodeLab.layoutChain + .left() + .rightToView(phoneLineView) + .centerY() + + phoneInputTF.layoutChain + .leftToView(phoneLineView, offset: 13) + .right() + .edgesVertical() + + smsCodeInputView.layoutChain + .topToBottomOfView(phoneInputView, offset: 20) + .edges(excludingEdge: .top) + .widthToView(phoneInputView) + .heightToView(phoneInputView) + + smsCodeBtn.layoutChain + .edgesVertical() + .right() + .width(100) + + smsCodeTF.layoutChain + .edgesVertical() + .left(20) + .rightToLeftOfView(smsCodeBtn) + + loginButton.layoutChain + .topToBottomOfView(otherPhoneView, offset: 63) + .centerX() + .width(247) + .height(50) + + agreementView.layoutChain + .leftToView(loginButton) + .rightToView(loginButton) + .bottom(55) + .height(30) + + agreementLabel.layoutChain.edges() + + checkBox.layoutChain + .left() + .centerY() + .width(12) + .height(12) + + agreementTV.layoutChain + .leftToRightOfView(checkBox, offset: 0) + .right() + .top() + + phoneLoginBtn.layoutChain + .bottomToTopOfView(agreementView, offset: -81) + .centerX() + .width(38) + .heightToWidth(1) + + appleLoginBtn.layoutChain + .rightToLeftOfView(phoneLoginBtn, offset: -43) + .centerY(phoneLoginBtn) + .widthToView(phoneLoginBtn) + .heightToView(phoneLoginBtn) + + wechatLoginBtn.layoutChain + .leftToRightOfView(phoneLoginBtn, offset: 43) + .centerY(phoneLoginBtn) + .widthToView(phoneLoginBtn) + .heightToView(phoneLoginBtn) + } + + override init(frame: CGRect) { + super.init(frame: .zero) + backgroundColor = .white + setupUI() + setupRx() + setupAgreementTextWithCarrier(carrier: "") + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - UI Components + lazy var bgMaskImage: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Login/bg") + iv.contentMode = .scaleAspectFill + return iv + }() + + lazy var backBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Common/back"), for: .normal) + btn.extendEdgeInsets = UIEdgeInsets(top: 54, left: 15, bottom: 50, right: 50) + return btn + }() + + lazy var guestLoginButton: UIButton = { + let btn = UIButton(type: .system) + btn.setTitle("游客登录", for: .normal) + btn.setTitleColor(.white, for: .normal) + btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium) + btn.setBackgroundImage(UIImage(named: "Login/visitor_bg"), for: .normal) + return btn + }() + + lazy var welcomeLabel: UILabel = { + let label = UILabel() + label.text = "欢迎登录" + label.font = UIFont(name: "DOUYU Font", size: 24) + label.textColor = UIColor(hexStr: "#030303") + label.textAlignment = .center + return label + }() + + lazy var phoneNumberLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 20, weight: .medium) + label.textColor = ThemeManager.shared.color.titleAuxColor + label.textAlignment = .center + return label + }() + + lazy var carrierLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 12) + label.textColor = ThemeManager.shared.color.contentColor + label.textAlignment = .center + return label + }() + + // 其他手机号登录 + lazy var otherPhoneView: UIView = { + let view = UIView() + view.backgroundColor = .clear +// view.isHidden = true + return view + }() + + // 手机号 + lazy var phoneInputView: UIView = { + let view = UIView() + view.backgroundColor = .clear + view.borderWidth = 1 + view.borderColor = .white + view.cornerRadius = 8 + view.addSubview(areaCodeLab) + view.addSubview(phoneLineView) + view.addSubview(phoneInputTF) + return view + }() + + lazy var areaCodeLab: UILabel = { + let label = UILabel() + label.text = "+86" + label.font = .systemFont(ofSize: 16, weight: .medium) + label.textColor = .white + label.textAlignment = .center + return label + }() + + lazy var phoneLineView: UIView = { + let view = UIView() + view.backgroundColor = .white + return view + }() + + lazy var phoneInputTF: UITextField = { + let textField = UITextField() + textField.font = .systemFont(ofSize: 16, weight: .medium) + textField.placeholderColor(placeholder: "请输入手机号码", + color: .white) +// textField.tintColor = ThemeManager.shared.color.mainColor + textField.clearButtonMode = .whileEditing + textField.keyboardType = .numberPad + return textField + }() + + // 验证码 + lazy var smsCodeInputView: UIView = { + let view = UIView() + view.backgroundColor = .clear + view.borderWidth = 1 + view.borderColor = .white + view.cornerRadius = 8 + view.addSubview(smsCodeTF) + view.addSubview(smsCodeBtn) + return view + }() + + lazy var smsCodeTF: UITextField = { + let textField = UITextField() + textField.font = .systemFont(ofSize: 16, weight: .medium) + textField.placeholderColor(placeholder: "请输入验证码", + color: .white) + textField.keyboardType = .numbersAndPunctuation + return textField + }() + + lazy var smsCodeBtn: UIButton = { + let button = UIButton() + button.setTitle("获取验证码", for: .normal) + button.setTitleColor(UIColor(hexStr: "#030303"), for: .normal) + button.setTitleColor(UIColor(hexStr: "#999999", alpha: 1.0), for: .disabled) + button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + return button + }() + + lazy var loginButton: UIButton = { + let btn = UIButton(type: .system) + btn.setTitle("立即登录", for: .normal) + btn.setTitleColor(UIColor(hexStr: "#0F2846"), for: .normal) + btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + btn.setBackgroundImage(UIImage(named: "Login/login_bg"), for: .normal) + return btn + }() + + lazy var wechatLoginBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setBackgroundImage(UIImage(named: "Login/wechat"), for: .normal) + btn.backgroundColor = .clear + return btn + }() + + lazy var appleLoginBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setBackgroundImage(UIImage(named: "Login/apple"), for: .normal) + btn.backgroundColor = .clear + return btn + }() + + lazy var phoneLoginBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setBackgroundImage(UIImage(named: "Login/phone"), for: .normal) + btn.backgroundColor = .clear + return btn + }() + + lazy var agreementView: UIView = { + let view = UIView() + view.backgroundColor = .clear + return view + }() + + lazy var checkBox: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Login/checkbox"), for: .normal) + btn.setImage(UIImage(named: "Login/selected"), for: .selected) + btn.extendEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) + return btn + }() + + lazy var agreementLabel: UILabel = { + let label = UILabel() + label.textColor = .clear + label.numberOfLines = 1 + label.textAlignment = .center + label.font = .systemFont(ofSize: 10) + return label + }() + + lazy var agreementTV: UITextView = { + let textView = UITextView() + textView.font = .systemFont(ofSize: 10, weight: .medium) + textView.backgroundColor = .clear + textView.isEditable = false + textView.isScrollEnabled = false + textView.isSelectable = false + textView.linkTextAttributes = [:] + + return textView + }() +} diff --git a/QuickLocation/Section/Login/LoginViewController.swift b/QuickLocation/Section/Login/LoginViewController.swift new file mode 100644 index 00000000..4b5faeb6 --- /dev/null +++ b/QuickLocation/Section/Login/LoginViewController.swift @@ -0,0 +1,164 @@ +// +// LoginViewController.swift +// QuickLocation +// +// Created based on Lanhu design: 登录-一键登录 +// + +import UIKit +import SnapKit +import RxSwift +import RxCocoa +#if !targetEnvironment(simulator) +import GeYanSdk +#endif + +class LoginViewController: BaseViewController { + + override var isNavigationBarHidden: Bool { true } + override var preferredStatusBarStyle: UIStatusBarStyle { .default } + + // MARK: - Properties + fileprivate var rootView: LoginView! + + private let viewModel = LoginViewModel() + private var isAgreed = false + private var countDownService = CountDownService(countDownTime: 60) + + + + // MARK: - Lifecycle + override func loadView() { + rootView = LoginView(frame: UIScreen.main.bounds) + view = rootView + } + + override func viewDidLoad() { + super.viewDidLoad() + rootView.agreementTV.delegate = self + bindViewModel() + reactiveAction() + } + + private func reactiveAction() { + rootView.smsCodeBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in + guard let self = self, let phone = self.rootView.phoneInputTF.text else { return } + self.requestSmsCode(phone: phone, + sendBtn: rootView.smsCodeBtn, + countDownService: self.countDownService) + }.disposed(by: rootView.disposeBag) + + rootView.phoneLoginBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in + guard let self = self else { return } + + let oneTapLoginView = OneTapLoginView(frame: self.view.bounds) + let list = [oneTapLoginView.phoneNumberLabel, + oneTapLoginView.carrierLabel, + oneTapLoginView.loginButton, + oneTapLoginView.checkBox, + oneTapLoginView.agreementLabel] + GeYanSdk.oneTapLogin(self, + viewModel: self.viewModel.gyAuthVM, + contentView: oneTapLoginView, + subViewList: list) { data in + guard let responseData = data, + let code = responseData["code"] as? Int else { return } + print(responseData) + if code == 30000 { // 成功 + let gyuid = responseData["gyuid"] + let token = responseData["token"] + let requestData = ["gyuid" : gyuid, "token": token] + self.viewModel.loginAction(type: "onekey", data: requestData) + } + else { + DLToast.showError(text: responseData["msg"] as? String ?? "运营商返回失败") + } + } + }.disposed(by: disposeBag) + } + + // MARK: - Bindings + private func bindViewModel() { + rootView.checkBox.rx.tap + .subscribe(onNext: { [weak self] in + self?.isAgreed.toggle() + self?.rootView.checkBox.isSelected = self?.isAgreed ?? false + }) + .disposed(by: disposeBag) + + rootView.loginButton.rx.tap + .subscribe(onNext: { [weak self] in + guard let self = self else { return } + + if !self.isAgreed { + DLToast.showError(text: "请先同意用户协议") + return + } + + if let phone = self.rootView.phoneInputTF.text, phone.isEmpty { + DLToast.showError(text: "请输入手机号码") + } + else if let smsCode = self.rootView.smsCodeTF.text, smsCode.isEmpty { + DLToast.showError(text: "请输入验证码") + } + else { + self.viewModel.loginAction(type: "phone", data: ["TODO": ""]) + } + }) + .disposed(by: disposeBag) + + rootView.guestLoginButton.rx.tap + .subscribe(onNext: { _ in + AppDelegate.shared.showMainViewController() + }) + .disposed(by: disposeBag) + + rootView.wechatLoginBtn.rx.tap + .subscribe(onNext: { [weak self] in + self?.viewModel.performWechatLogin() + }) + .disposed(by: disposeBag) + + rootView.appleLoginBtn.rx.tap + .subscribe(onNext: { [weak self] in + self?.viewModel.performAppleLogin() + }) + .disposed(by: disposeBag) + + rootView.phoneLoginBtn.rx.tap + .subscribe(onNext: { [weak self] in + + }) + .disposed(by: disposeBag) + + viewModel.loginSuccess + .subscribe(onNext: { [weak self] in + + }) + .disposed(by: disposeBag) + } +} + +extension LoginViewController: UITextViewDelegate { + func textView(_ textView: UITextView, + shouldInteractWith URL: URL, + in characterRange: NSRange, + interaction: UITextItemInteraction) -> Bool { +// if URL.absoluteString == "Carrier", let model = GyContentModel.current(), let link = model.link { +// AppRouter.push(Route.web, userInfo: ["url": link]) +// } + if URL.absoluteString == "UserAgreement" { + AppRouter.push(Route.web, userInfo: ["url": URLManager.shared.userAgreementUrl]) + } + if URL.absoluteString == "PrivacyPolicy" { + AppRouter.push(Route.web, userInfo: ["url": URLManager.shared.privacyPolicyUrl]) + } + return true + } + + func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { + false + } + + private func openURL(_ url: String) {} +} diff --git a/QuickLocation/Section/Login/LoginViewModel.swift b/QuickLocation/Section/Login/LoginViewModel.swift new file mode 100644 index 00000000..5d180e55 --- /dev/null +++ b/QuickLocation/Section/Login/LoginViewModel.swift @@ -0,0 +1,62 @@ +// +// LoginViewModel.swift +// QuickLocation +// + +import Foundation +import RxSwift +#if !targetEnvironment(simulator) +import GeYanSdk +#endif + +final class LoginViewModel: BaseViewModel { + + let oneClickLoginResult = PublishSubject() + let loginSuccess = PublishSubject() + + var gyAuthVM: GyAuthViewModel { + let viewModel = GyAuthViewModel() + viewModel.statusBarStyle = .default + viewModel.userInterfaceStyle = 0 + viewModel.pullAuthVCStyle = .push + viewModel.viewLifeCycleBlock = { (str, bool) in + + } + viewModel.clickAuthButtonBlock = { + return true + } + return viewModel + } + + /// 登录 + func loginAction(type: String, data: [String : Any]) { + DLToast.showLoading() + UserService.login(type: type, data: data).subscribe { response in + guard let model = response.model else { return } + if AppContextManager.shared.saveAccount(model) { + DLToast.showSuccess(text: "登录成功") { + AppRouter.shared.popToRoot() + } + } + else { + DLToast.show(text: "登录失败,请重新尝试") + } + }.disposed(by: disposeBag) + } + + func performGuestLogin() { + loginSuccess.onNext(()) + } + + func performWechatLogin() { + // TODO: Integrate WeChat SDK + } + + func performAppleLogin() { + // TODO: Integrate Sign in with Apple + } + + func performQQLogin() { + // TODO: Integrate QQ SDK + } +} diff --git a/QuickLocation/Section/Login/OneTapLoginView.swift b/QuickLocation/Section/Login/OneTapLoginView.swift new file mode 100644 index 00000000..0d8bc1f4 --- /dev/null +++ b/QuickLocation/Section/Login/OneTapLoginView.swift @@ -0,0 +1,215 @@ +// +// OneTapLoginView.swift +// QuickLocation +// +// Created by 八条 on 2026/5/28. +// + +import UIKit +import RxSwift +import RxCocoa +#if !targetEnvironment(simulator) +import GeYanSdk +#endif + +class OneTapLoginView: UIView { + + var disposeBag = DisposeBag() + var oneTapLogin = true + + private func setupRx() { + backBtn.rx.tap.subscribe(onNext: { _ in + AppRouter.shared.popOrDismiss() + }).disposed(by: disposeBag) + + checkBox.rx.tap.subscribe(onNext: { [weak self] in + guard let self = self else { return } + self.checkBox.isSelected = !self.checkBox.isSelected + }).disposed(by: disposeBag) + } + + func setupAgreementTextWithCarrier(carrier: String) { + let text = "登录即同意\(carrier)、《隐私政策》和《用户协议》" + agreementLabel.text = text + // 创建段落样式 + let paragraphStyle = NSMutableParagraphStyle() + // 设置行距(lineSpacing 是行间距,lineHeightMultiple 是行高倍数) + paragraphStyle.lineSpacing = 4.0 // 行间距 + + let attributedString = NSMutableAttributedString(string: text) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#A4A7AE"), + .paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: text.length)) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#16B3FF"), + .link: "Carrier"], + range: (text as NSString).range(of: carrier)) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#16B3FF"), + .link: "UserAgreement"], + range: (text as NSString).range(of: "《用户协议》")) + attributedString.addAttributes([.foregroundColor: UIColor(hexStr: "#16B3FF"), + .link: "PrivacyPolicy"], + range: (text as NSString).range(of: "《隐私政策》")) + + agreementTV.attributedText = attributedString + } + + private func setupUI() { + addSubview(bgMaskImage) + addSubview(backBtn) + addSubview(welcomeLabel) + addSubview(phoneNumberLabel) + addSubview(carrierLabel) + addSubview(loginButton) + + addSubview(agreementView) + agreementView.addSubview(checkBox) + agreementView.addSubview(agreementTV) + agreementView.addSubview(agreementLabel) + + bgMaskImage.layoutChain.edges() + + backBtn.layoutChain + .top(54) + .left(15) + .width(24) + .height(24) + + welcomeLabel.layoutChain + .top(202 - kNaviHeight) + .centerX() + .edgesHorzontal() + + phoneNumberLabel.layoutChain + .topToBottomOfView(welcomeLabel, offset: 78) + .centerX() + + carrierLabel.layoutChain + .topToBottomOfView(phoneNumberLabel, offset: 4) + .centerX() + + loginButton.layoutChain + .topToBottomOfView(carrierLabel, offset: 99) + .centerX() + .width(247) + .height(50) + + agreementView.layoutChain + .leftToView(loginButton) + .rightToView(loginButton) + .bottom(55) + .height(30) + + agreementLabel.layoutChain.edges() + + checkBox.layoutChain + .left() + .centerY() + .width(12) + .height(12) + + agreementTV.layoutChain + .leftToRightOfView(checkBox, offset: 0) + .right() + .top() + } + + override init(frame: CGRect) { + super.init(frame: frame) + backgroundColor = .white + setupUI() + setupRx() + + if let model = GyContentModel.current() { + phoneNumberLabel.text = model.pn + carrierLabel.text = model.slogan + setupAgreementTextWithCarrier(carrier: model.term) + } + } + + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - UI Components + lazy var bgMaskImage: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Login/bg") + iv.contentMode = .scaleAspectFill + return iv + }() + + lazy var backBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Common/back"), for: .normal) + btn.extendEdgeInsets = UIEdgeInsets(top: 54, left: 15, bottom: 50, right: 50) + return btn + }() + + lazy var welcomeLabel: UILabel = { + let label = UILabel() + label.text = "欢迎登录" + label.font = UIFont(name: "DOUYU Font", size: 24) + label.textColor = UIColor(hexStr: "#030303") + label.textAlignment = .center + return label + }() + + lazy var phoneNumberLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 20, weight: .medium) + label.textColor = ThemeManager.shared.color.titleAuxColor + label.textAlignment = .center + return label + }() + + lazy var carrierLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 12) + label.textColor = ThemeManager.shared.color.contentColor + label.textAlignment = .center + return label + }() + + lazy var loginButton: UIButton = { + let btn = UIButton(type: .system) + btn.setTitle("本机号码一键登录", for: .normal) + btn.setTitleColor(UIColor(hexStr: "#0F2846"), for: .normal) + btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + btn.setBackgroundImage(UIImage(named: "Login/login_bg"), for: .normal) + return btn + }() + + lazy var agreementView: UIView = { + let view = UIView() + view.backgroundColor = .clear + return view + }() + + lazy var checkBox: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Login/checkbox"), for: .normal) + btn.setImage(UIImage(named: "Login/selected"), for: .selected) + btn.extendEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) + return btn + }() + + lazy var agreementLabel: UILabel = { + let label = UILabel() + label.textColor = .clear + label.numberOfLines = 1 + label.textAlignment = .center + label.font = .systemFont(ofSize: 10) + return label + }() + + lazy var agreementTV: UITextView = { + let textView = UITextView() + textView.font = .systemFont(ofSize: 10, weight: .medium) + textView.backgroundColor = .clear + textView.isEditable = false + textView.isScrollEnabled = false + textView.isSelectable = false + textView.linkTextAttributes = [:] + + return textView + }() +} diff --git a/QuickLocation/Section/Map/CircleMember.swift b/QuickLocation/Section/Map/CircleMember.swift new file mode 100644 index 00000000..d96171f5 --- /dev/null +++ b/QuickLocation/Section/Map/CircleMember.swift @@ -0,0 +1,85 @@ +// +// CircleMember.swift +// QuickLocation +// + +import Foundation +import CoreLocation + +struct CircleMember { + let id: String + let name: String + let avatar: String + let isOnline: Bool + let isOwner: Bool + let coordinate: CLLocationCoordinate2D + let address: String + let heading: Double + let lastUpdateText: String + + var isCurrentUser: Bool { id == "current" } +} + +// MARK: - Mock Data + +extension Array where Element == CircleMember { + static var mock: [CircleMember] { + [ + CircleMember( + id: "current", + name: "清月清月清月清月", + avatar: "map_avatar_1", + isOnline: true, + isOwner: true, + coordinate: CLLocationCoordinate2D(latitude: 29.5663, longitude: 106.5466), + address: "重庆市两江新区洪湖东路1号", + heading: 45, + lastUpdateText: "在线" + ), + CircleMember( + id: "m2", + name: "Ehahammy", + avatar: "map_avatar_2", + isOnline: false, + isOwner: false, + coordinate: CLLocationCoordinate2D(latitude: 29.5675, longitude: 106.5485), + address: "重庆市两江新区洪湖东路1号", + heading: 0, + lastUpdateText: "30分钟前" + ), + CircleMember( + id: "m3", + name: "热风环游", + avatar: "map_avatar_3", + isOnline: true, + isOwner: false, + coordinate: CLLocationCoordinate2D(latitude: 29.5650, longitude: 106.5450), + address: "重庆市两江新区洪湖东路1号", + heading: 0, + lastUpdateText: "在线" + ), + CircleMember( + id: "m4", + name: "孟佳清", + avatar: "map_avatar_4", + isOnline: false, + isOwner: false, + coordinate: CLLocationCoordinate2D(latitude: 29.5640, longitude: 106.5440), + address: "重庆市两江新区洪湖东路1号", + heading: 0, + lastUpdateText: "30分钟前" + ), + CircleMember( + id: "m5", + name: "林七夜", + avatar: "map_avatar_5", + isOnline: false, + isOwner: false, + coordinate: CLLocationCoordinate2D(latitude: 29.5630, longitude: 106.5430), + address: "重庆市两江新区洪湖东路1号", + heading: 0, + lastUpdateText: "30分钟前" + ) + ] + } +} diff --git a/QuickLocation/Section/Map/MapView.swift b/QuickLocation/Section/Map/MapView.swift new file mode 100644 index 00000000..bc243282 --- /dev/null +++ b/QuickLocation/Section/Map/MapView.swift @@ -0,0 +1,664 @@ +// +// MapView.swift +// QuickLocation +// +// Created based on Lanhu design: 1.主页.-成员 +// + +import UIKit +import RxSwift +#if !targetEnvironment(simulator) +import MAMapKit +#endif + +final class MapView: UIView { + + var disposeBag = DisposeBag() + + // MARK: - Design Constants (iOS points, from Lanhu design "1.主页.-成员" 375pt wide) + private let topNavHeight: CGFloat = 44 + private let controlButtonSize: CGFloat = 14 + private let controlStripWidth: CGFloat = 20 + private let controlStripCornerRadius: CGFloat = 10 + private let panelHeaderHeight: CGFloat = 70 + + private var bottomPanelHeightConstraint: NSLayoutConstraint? + + // MARK: - Fonts + private let douyuFont: (CGFloat) -> UIFont? = { size in + UIFont(name: "DOUYU Font", size: size) + } + private let pingFangMedium: (CGFloat) -> UIFont = { size in + UIFont(name: "PingFangSC-Medium", size: size) ?? UIFont.systemFont(ofSize: size, weight: .medium) + } + private let pingFangSemibold: (CGFloat) -> UIFont = { size in + UIFont(name: "PingFangSC-Semibold", size: size) ?? UIFont.systemFont(ofSize: size, weight: .semibold) + } + private let pingFangRegular: (CGFloat) -> UIFont = { size in + UIFont(name: "PingFangSC-Regular", size: size) ?? UIFont.systemFont(ofSize: size, weight: .regular) + } + + // MARK: - Top Navigation Bar + private(set) lazy var topNavBar: UIView = { + let v = UIView() + v.backgroundColor = .clear + return v + }() + + private(set) lazy var avatarButton: UIButton = { + let btn = UIButton(type: .custom) + btn.layer.cornerRadius = 18 + btn.clipsToBounds = true + btn.backgroundColor = UIColor(hexStr: "#E0E0E0") + btn.setImage(UIImage(named: "map_avatar_1"), for: .normal) + return btn + }() + + private lazy var titleLabel: UILabel = { + let l = UILabel() + l.text = "我的圈子" + l.font = pingFangMedium(14) + l.textColor = UIColor(hexStr: "#0F2846") + return l + }() + + private lazy var goldCircleIcon: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Map/map_circle_icon") + iv.contentMode = .scaleAspectFit + return iv + }() + + private(set) lazy var dropdownArrowButton: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(systemName: "chevron.down"), for: .normal) + btn.tintColor = UIColor(hexStr: "#0F2846") + return btn + }() + + // MARK: - Map View + #if !targetEnvironment(simulator) + lazy var mapView: MAMapView = { + let mv = MAMapView() + mv.zoomLevel = 15 + mv.minZoomLevel = 3 + mv.maxZoomLevel = 20 + mv.showsUserLocation = true + mv.userTrackingMode = .follow + mv.showsCompass = false + mv.showsScale = false + mv.isRotateEnabled = false + mv.isRotateCameraEnabled = false + return mv + }() + #else + lazy var mapPlaceholderView: UIView = { + let v = UIView() + v.backgroundColor = UIColor(hexStr: "#EDEDED") + let label = UILabel() + label.text = "Map requires a real device" + label.font = UIFont.systemFont(ofSize: 14) + label.textColor = UIColor(hexStr: "#999999") + label.textAlignment = .center + v.addSubview(label) + label.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + label.centerXAnchor.constraint(equalTo: v.centerXAnchor), + label.centerYAnchor.constraint(equalTo: v.centerYAnchor) + ]) + return v + }() + #endif + + // MARK: - Map Controls (Left Side) + private lazy var controlStrip: UIView = { + let v = UIView() + v.backgroundColor = UIColor.black.withAlphaComponent(0.5) + v.layer.cornerRadius = controlStripCornerRadius + v.clipsToBounds = true + return v + }() + + private func makeControlButton(icon: String, text: String) -> UIView { + let container = UIView() + + let circleBtn = UIView() + circleBtn.backgroundColor = .white + circleBtn.layer.cornerRadius = controlButtonSize / 2 + container.addSubview(circleBtn) + + let imgView = UIImageView() + imgView.image = UIImage(named: "Map/\(icon)") + imgView.contentMode = .scaleAspectFit + circleBtn.addSubview(imgView) + + let label = UILabel() + label.text = text + label.font = pingFangMedium(8) + label.textColor = .white + label.textAlignment = .center + container.addSubview(label) + + circleBtn.layoutChain + .top(0).centerX() + .size(CGSize(width: controlButtonSize, height: controlButtonSize)) + + imgView.layoutChain + .center().size(CGSize(width: 8, height: 8)) + + label.layoutChain + .topToBottomOfView(circleBtn, offset: 3) + .centerX().bottom() + + return container + } + + private(set) lazy var sosButton: UIView = makeControlButton(icon: "map_btn_sos", text: "SOS") + private(set) lazy var checkinButton: UIView = makeControlButton(icon: "map_btn_checkin", text: "签到") + private(set) lazy var bubbleButton: UIView = makeControlButton(icon: "map_btn_trip", text: "气泡") + + // MARK: - Siren Button (left of control strip) + private(set) lazy var sirenButton: UIButton = { + let btn = UIButton(type: .custom) + btn.backgroundColor = .clear + btn.setImage(UIImage(named: "Map/map_member_bubble_large"), for: .normal) + btn.contentMode = .scaleAspectFit + return btn + }() + + // MARK: - Location Button (Bottom-Right) + private(set) lazy var locationButton: UIButton = { + let btn = UIButton(type: .custom) + btn.backgroundColor = UIColor.black.withAlphaComponent(0.4) + btn.layer.cornerRadius = 10 + btn.setImage(UIImage(named: "Map/map_current_location"), for: .normal) + btn.contentMode = .center + return btn + }() + + // MARK: - Announcement Bar + private(set) lazy var announcementBar: UIView = { + let v = UIView() + v.backgroundColor = UIColor.white + v.layer.cornerRadius = 11 + v.layer.shadowColor = UIColor.black.withAlphaComponent(0.08).cgColor + v.layer.shadowOffset = CGSize(width: 0, height: 2) + v.layer.shadowRadius = 6 + v.layer.shadowOpacity = 1 + v.isHidden = true + return v + }() + + private lazy var announcementLabel: UILabel = { + let l = UILabel() + l.font = pingFangRegular(11) + l.textColor = UIColor(hexStr: "#0F2846") + return l + }() + + private(set) lazy var announcementCloseBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(systemName: "xmark"), for: .normal) + btn.tintColor = UIColor(hexStr: "#999999") + return btn + }() + + // MARK: - Bottom Panel + private(set) lazy var bottomPanel: UIView = { + let v = UIView() + v.backgroundColor = .white + v.layer.cornerRadius = 16 + v.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] + v.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor + v.layer.shadowOffset = CGSize(width: 0, height: -2) + v.layer.shadowRadius = 6 + v.layer.shadowOpacity = 1 + return v + }() + + // Panel header background image + private lazy var panelHeaderBg: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Map/map_top_panel") + iv.contentMode = .scaleToFill + return iv + }() + + private lazy var circleIcon: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Map/map_circle_icon") + iv.contentMode = .scaleAspectFit + return iv + }() + + private lazy var memberListTitleLabel: UILabel = { + let l = UILabel() + l.text = "圈子成员" + l.font = douyuFont(16) ?? pingFangSemibold(16) + l.textColor = .white + return l + }() + + private(set) lazy var memberCountLabel: UILabel = { + let l = UILabel() + l.font = pingFangRegular(11) + l.textColor = UIColor(hexStr: "#0F2846").withAlphaComponent(0.7) + return l + }() + + private(set) lazy var refreshButton: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Map/map_btn_menu"), for: .normal) + btn.contentMode = .scaleAspectFit + return btn + }() + + private(set) lazy var inviteButton: UIButton = { + let btn = UIButton(type: .custom) + btn.setTitle("邀请加入", for: .normal) + btn.titleLabel?.font = pingFangMedium(11) + btn.setTitleColor(.white, for: .normal) + btn.backgroundColor = UIColor.white.withAlphaComponent(0.2) + btn.layer.cornerRadius = 12 + return btn + }() + + // MARK: - Member List + private(set) lazy var memberListScrollView: UIScrollView = { + let sv = UIScrollView() + sv.showsVerticalScrollIndicator = false + sv.alwaysBounceVertical = true + sv.backgroundColor = .white + return sv + }() + + private lazy var memberListStackView: UIStackView = { + let sv = UIStackView() + sv.axis = .vertical + sv.spacing = 0 + return sv + }() + + // MARK: - Init + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupLayout() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - Setup + private func setupUI() { + backgroundColor = .white + + addSubview(topNavBar) + topNavBar.addSubview(avatarButton) + topNavBar.addSubview(titleLabel) + topNavBar.addSubview(goldCircleIcon) + topNavBar.addSubview(dropdownArrowButton) + + #if !targetEnvironment(simulator) + addSubview(mapView) + #else + addSubview(mapPlaceholderView) + #endif + + addSubview(controlStrip) + controlStrip.addSubview(sosButton) + controlStrip.addSubview(checkinButton) + controlStrip.addSubview(bubbleButton) + + addSubview(sirenButton) + addSubview(locationButton) + addSubview(announcementBar) + announcementBar.addSubview(announcementLabel) + announcementBar.addSubview(announcementCloseBtn) + + addSubview(bottomPanel) + bottomPanel.addSubview(panelHeaderBg) + bottomPanel.addSubview(circleIcon) + bottomPanel.addSubview(memberListTitleLabel) + bottomPanel.addSubview(memberCountLabel) + bottomPanel.addSubview(refreshButton) + bottomPanel.addSubview(inviteButton) + bottomPanel.addSubview(memberListScrollView) + memberListScrollView.addSubview(memberListStackView) + } + + private func setupLayout() { + topNavBar.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + topNavBar.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), + topNavBar.leadingAnchor.constraint(equalTo: leadingAnchor), + topNavBar.trailingAnchor.constraint(equalTo: trailingAnchor), + topNavBar.heightAnchor.constraint(equalToConstant: topNavHeight) + ]) + + avatarButton.layoutChain + .left(12).centerY() + .size(CGSize(width: 36, height: 36)) + + titleLabel.layoutChain.center() + + goldCircleIcon.layoutChain + .leftToRightOfView(titleLabel, offset: 4) + .centerY(titleLabel) + .size(CGSize(width: 18, height: 14)) + + dropdownArrowButton.layoutChain + .right(12).centerY() + .size(CGSize(width: 20, height: 20)) + + #if !targetEnvironment(simulator) + mapView.layoutChain + .topToBottomOfView(topNavBar) + .left(0).right(0).bottom(0) + #else + mapPlaceholderView.layoutChain + .topToBottomOfView(topNavBar) + .left(0).right(0).bottom(0) + #endif + + // Left control strip + controlStrip.layoutChain + .left(8) + .topToBottomOfView(topNavBar, offset: 12) + .width(controlStripWidth) + + sosButton.layoutChain + .top(10).centerX() + .left(0).right(0) + .height(30) + + checkinButton.layoutChain + .topToBottomOfView(sosButton, offset: 12) + .centerX() + .left(0).right(0) + .height(30) + + bubbleButton.layoutChain + .topToBottomOfView(checkinButton, offset: 12) + .centerX() + .left(0).right(0) + .height(30) + .bottom(10) + + // Siren (alarm) button to the left of control strip + sirenButton.layoutChain + .leftToRightOfView(controlStrip, offset: 6) + .centerY(controlStrip) + .size(CGSize(width: 28, height: 28)) + + // Location button + locationButton.layoutChain + .right(12) + .bottomToTopOfView(bottomPanel, offset: -12) + .size(CGSize(width: 20, height: 20)) + + // Announcement bar + announcementBar.layoutChain + .left(24).right(24) + .topToBottomOfView(topNavBar, offset: 8) + .height(22) + + announcementLabel.layoutChain + .left(12).centerY() + + announcementCloseBtn.layoutChain + .right(8).centerY() + .size(CGSize(width: 10, height: 10)) + + // Bottom panel + bottomPanel.layoutChain + .left(0).right(0).bottom(0) + + bottomPanel.translatesAutoresizingMaskIntoConstraints = false + let hc = bottomPanel.heightAnchor.constraint(equalToConstant: bottomPanelHeight(for: bounds.height)) + hc.isActive = true + bottomPanelHeightConstraint = hc + + // Panel header + panelHeaderBg.layoutChain + .top(0).left(0).right(0) + .height(panelHeaderHeight) + + circleIcon.layoutChain + .left(12).top(12) + .size(CGSize(width: 26, height: 26)) + + memberListTitleLabel.layoutChain + .leftToRightOfView(circleIcon, offset: 6) + .centerY(circleIcon) + + memberCountLabel.layoutChain + .leftToRightOfView(circleIcon, offset: 6) + .topToBottomOfView(memberListTitleLabel, offset: 2) + + refreshButton.layoutChain + .rightToLeftOfView(inviteButton, offset: -12) + .centerY(circleIcon) + .size(CGSize(width: 16, height: 16)) + + inviteButton.layoutChain + .right(12).centerY(circleIcon) + .size(CGSize(width: 64, height: 24)) + + // Member list scroll view + memberListScrollView.layoutChain + .topToBottomOfView(panelHeaderBg) + .left(0).right(0).bottom(0) + + memberListStackView.layoutChain + .top(0).left(0) + .widthToView(memberListScrollView) + } + + override func layoutSubviews() { + super.layoutSubviews() + bottomPanelHeightConstraint?.constant = bottomPanelHeight(for: bounds.height) + } + + /// Bottom panel is ~42% of view height, capped between 280-350pt + private func bottomPanelHeight(for totalHeight: CGFloat) -> CGFloat { + let ratio: CGFloat = 0.42 + return min(350, max(280, totalHeight * ratio)) + } + + // MARK: - Configure Member List + func configureMemberList(with members: [CircleMember], onSelect: @escaping (CircleMember) -> Void) { + memberListStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } + + let onlineCount = members.filter { $0.isOnline }.count + memberCountLabel.text = "共\(members.count)成员 / \(onlineCount)在线" + + for (index, member) in members.enumerated() { + let row = MemberRowView(member: member) + row.tag = index + let tap = UITapGestureRecognizer(target: self, action: #selector(memberRowTapped(_:))) + row.addGestureRecognizer(tap) + memberListStackView.addArrangedSubview(row) + + if index < members.count - 1 { + let sep = UIView() + sep.backgroundColor = UIColor(hexStr: "#F0F0F0") + memberListStackView.addArrangedSubview(sep) + sep.layoutChain.height(0.5) + } + } + + let totalContentHeight = CGFloat(members.count) * MemberRowView.rowHeight + + CGFloat(max(0, members.count - 1)) * 0.5 + memberListScrollView.contentSize = CGSize( + width: memberListScrollView.bounds.width, + height: max(totalContentHeight, memberListScrollView.bounds.height) + ) + } + + @objc private func memberRowTapped(_ gesture: UITapGestureRecognizer) { + // Handled via bindings in ViewController + } +} + +// MARK: - MemberRowView +final class MemberRowView: UIView { + + static let rowHeight: CGFloat = 38 + + private let avatarImageView: UIImageView = { + let iv = UIImageView() + iv.contentMode = .scaleAspectFill + iv.layer.cornerRadius = 12.5 + iv.layer.borderWidth = 1 + iv.layer.borderColor = UIColor.white.cgColor + iv.clipsToBounds = true + iv.backgroundColor = UIColor(hexStr: "#E0E0E0") + return iv + }() + + private let onlineDot: UIView = { + let v = UIView() + v.layer.cornerRadius = 4 + v.layer.borderWidth = 1 + v.layer.borderColor = UIColor.white.cgColor + return v + }() + + private let nameLabel: UILabel = { + let l = UILabel() + l.font = UIFont(name: "PingFangSC-Semibold", size: 12) + ?? UIFont.systemFont(ofSize: 12, weight: .semibold) + l.textColor = UIColor(hexStr: "#0F2846") + return l + }() + + private let addressLabel: UILabel = { + let l = UILabel() + l.font = UIFont(name: "PingFangSC-Regular", size: 10) + ?? UIFont.systemFont(ofSize: 10) + l.textColor = UIColor(hexStr: "#8D8D8D") + return l + }() + + private let statusBadge: UIView = { + let v = UIView() + v.layer.cornerRadius = 4 + return v + }() + + private let statusLabel: UILabel = { + let l = UILabel() + l.font = UIFont(name: "PingFangSC-Medium", size: 9) + ?? UIFont.systemFont(ofSize: 9, weight: .medium) + l.textAlignment = .center + return l + }() + + private let timeLabel: UILabel = { + let l = UILabel() + l.font = UIFont(name: "PingFangSC-Regular", size: 10) + ?? UIFont.systemFont(ofSize: 10) + l.textColor = UIColor(hexStr: "#999999") + return l + }() + + private lazy var navButton: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Map/map_current_location"), for: .normal) + btn.contentMode = .scaleAspectFit + return btn + }() + + let member: CircleMember + + init(member: CircleMember) { + self.member = member + super.init(frame: .zero) + setupUI() + configure() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setupUI() { + addSubview(avatarImageView) + addSubview(onlineDot) + addSubview(nameLabel) + addSubview(addressLabel) + addSubview(statusBadge) + statusBadge.addSubview(statusLabel) + addSubview(timeLabel) + addSubview(navButton) + + avatarImageView.layoutChain + .left(12).centerY() + .size(CGSize(width: 25, height: 25)) + + onlineDot.layoutChain + .rightToView(avatarImageView, offset: 2) + .bottomToView(avatarImageView, offset: 2) + .size(CGSize(width: 8, height: 8)) + + nameLabel.layoutChain + .leftToRightOfView(avatarImageView, offset: 8) + .top(6) + + addressLabel.layoutChain + .leftToRightOfView(avatarImageView, offset: 8) + .topToBottomOfView(nameLabel, offset: 2) + + statusBadge.layoutChain + .leftToRightOfView(nameLabel, offset: 6) + .centerY(nameLabel) + .height(16) + + statusLabel.layoutChain + .left(6).right(6).centerY() + + timeLabel.layoutChain + .rightToLeftOfView(navButton, offset: -4) + .centerY() + + navButton.layoutChain + .right(12).centerY() + .size(CGSize(width: 15, height: 15)) + + self.layoutChain.height(Self.rowHeight) + } + + private func configure() { + avatarImageView.image = UIImage(named: member.avatar) + + if member.isOnline { + onlineDot.backgroundColor = UIColor(hexStr: "#4CD964") + } else { + onlineDot.backgroundColor = UIColor(hexStr: "#D4D4D4") + } + onlineDot.isHidden = false + + nameLabel.text = member.name + addressLabel.text = "在 \(member.address)" + + if member.isOwner { + statusBadge.backgroundColor = UIColor(hexStr: "#9FD9FF") + statusLabel.text = "圈主" + statusLabel.textColor = UIColor(hexStr: "#194045") + } else if member.isOnline { + statusBadge.backgroundColor = UIColor(hexStr: "#9FD9FF") + statusLabel.text = "在线" + statusLabel.textColor = UIColor(hexStr: "#194045") + } else { + statusBadge.backgroundColor = UIColor(hexStr: "#EDEDED") + statusLabel.text = "离线" + statusLabel.textColor = UIColor(hexStr: "#999999") + } + + timeLabel.text = member.lastUpdateText + + backgroundColor = member.isCurrentUser ? UIColor(hexStr: "#EFF9FF") : .clear + } +} diff --git a/QuickLocation/Section/Map/MapViewController.swift b/QuickLocation/Section/Map/MapViewController.swift new file mode 100644 index 00000000..c12fbb08 --- /dev/null +++ b/QuickLocation/Section/Map/MapViewController.swift @@ -0,0 +1,223 @@ +// +// MapViewController.swift +// QuickLocation +// + +import UIKit +import RxSwift +import RxCocoa +import CoreLocation +#if !targetEnvironment(simulator) +import MAMapKit +#endif + +final class MapViewController: BaseViewController { + + override var isNavigationBarHidden: Bool { true } + override var preferredStatusBarStyle: UIStatusBarStyle { .darkContent } + + // MARK: - Properties + fileprivate var rootView: MapView! + private let viewModel = MapViewModel() + private let locationManager = CLLocationManager() + private var currentHeading: Double = 0 + + // MARK: - Lifecycle + override func loadView() { + #if !targetEnvironment(simulator) + MAMapView.updatePrivacyAgree(.didAgree) + MAMapView.updatePrivacyShow(.didShow, privacyInfo: .didContain) + #endif + + rootView = MapView(frame: UIScreen.main.bounds) + view = rootView + } + + override func viewDidLoad() { + super.viewDidLoad() + setupMap() + setupLocation() + bindViewModel() + bindUI() + viewModel.loadMembers() + } + + // MARK: - Map Setup + private func setupMap() { + #if !targetEnvironment(simulator) + rootView.mapView.delegate = self + #endif + } + + private func setupLocation() { + locationManager.delegate = self + locationManager.desiredAccuracy = kCLLocationAccuracyBest + locationManager.requestWhenInUseAuthorization() + locationManager.startUpdatingHeading() + } + + // MARK: - Bindings + private func bindViewModel() { + viewModel.output.members + .subscribe(onNext: { [weak self] members in + self?.updateAnnotations(with: members) + self?.rootView.configureMemberList(with: members) { member in + self?.viewModel.selectMember(member) + } + }) + .disposed(by: disposeBag) + + viewModel.output.trackingMode + .subscribe(onNext: { [weak self] tracking in + #if !targetEnvironment(simulator) + self?.rootView.mapView.userTrackingMode = tracking ? .follow : .none + #endif + }) + .disposed(by: disposeBag) + + viewModel.selectedMember + .subscribe(onNext: { [weak self] member in + self?.focusOnMember(member) + }) + .disposed(by: disposeBag) + } + + private func bindUI() { + // Left control buttons + let sosTap = UITapGestureRecognizer() + rootView.sosButton.addGestureRecognizer(sosTap) + sosTap.rx.event.subscribe(onNext: { _ in print("SOS tapped") }) + .disposed(by: disposeBag) + + let checkinTap = UITapGestureRecognizer() + rootView.checkinButton.addGestureRecognizer(checkinTap) + checkinTap.rx.event.subscribe(onNext: { _ in print("Check-in tapped") }) + .disposed(by: disposeBag) + + let bubbleTap = UITapGestureRecognizer() + rootView.bubbleButton.addGestureRecognizer(bubbleTap) + bubbleTap.rx.event.subscribe(onNext: { _ in print("Bubble tapped") }) + .disposed(by: disposeBag) + + // Location button + rootView.locationButton.rx.tap + .subscribe(onNext: { [weak self] in + self?.viewModel.toggleTracking() + }) + .disposed(by: disposeBag) + + // Refresh button + rootView.refreshButton.rx.tap + .subscribe(onNext: { [weak self] in + self?.viewModel.loadMembers() + }) + .disposed(by: disposeBag) + + // Invite button + rootView.inviteButton.rx.tap + .subscribe(onNext: { _ in print("Invite tapped") }) + .disposed(by: disposeBag) + + // Avatar button + rootView.avatarButton.rx.tap + .subscribe(onNext: { _ in print("Avatar tapped") }) + .disposed(by: disposeBag) + + // Announcement close + rootView.announcementCloseBtn.rx.tap + .subscribe(onNext: { [weak self] in + self?.rootView.announcementBar.isHidden = true + }) + .disposed(by: disposeBag) + } + + // MARK: - Annotations + private func updateAnnotations(with members: [CircleMember]) { + #if !targetEnvironment(simulator) + let existing = rootView.mapView.annotations ?? [] + let existingMemberIDs = Set(existing.compactMap { ($0 as? MemberAnnotation)?.member.id }) + let newMemberIDs = Set(members.map { $0.id }) + + let toRemove = existing.filter { ann in + guard let ma = ann as? MemberAnnotation else { return false } + return !newMemberIDs.contains(ma.member.id) + } + rootView.mapView.removeAnnotations(toRemove) + + let toAdd = members.filter { !existingMemberIDs.contains($0.id) } + let annotations = toAdd.map { MemberAnnotation(member: $0) } + rootView.mapView.addAnnotations(annotations) + #endif + } + + private func focusOnMember(_ member: CircleMember) { + #if !targetEnvironment(simulator) + rootView.mapView.setCenter(member.coordinate, animated: true) + #endif + } + + private func updateCurrentUserHeading() { + #if !targetEnvironment(simulator) + guard let annotations = rootView.mapView.annotations else { return } + for ann in annotations { + guard let ma = ann as? MemberAnnotation, ma.member.isCurrentUser else { continue } + if let view = rootView.mapView.view(for: ma) as? MemberAnnotationView { + view.updateHeading(currentHeading) + } + } + #endif + } +} + +#if !targetEnvironment(simulator) +// MARK: - MAMapViewDelegate +extension MapViewController: MAMapViewDelegate { + + func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! { + guard let memberAnnotation = annotation as? MemberAnnotation else { return nil } + + let identifier = "MemberAnnotation" + var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MemberAnnotationView + if annotationView == nil { + annotationView = MemberAnnotationView(annotation: memberAnnotation, reuseIdentifier: identifier) + } else { + annotationView?.annotation = memberAnnotation + } + + annotationView?.configure(with: memberAnnotation.member) + return annotationView + } + + func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) { + guard let annotation = view.annotation as? MemberAnnotation else { return } + viewModel.selectMember(annotation.member) + } + + func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) { + guard updatingLocation, let location = userLocation.location else { return } + if rootView.mapView.userTrackingMode == .follow { + rootView.mapView.setCenter(location.coordinate, animated: true) + } + } +} +#endif + +// MARK: - CLLocationManagerDelegate +extension MapViewController: CLLocationManagerDelegate { + + func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { + let h = newHeading.trueHeading + guard h >= 0 else { return } + currentHeading = h + updateCurrentUserHeading() + } + + func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { + if status == .authorizedWhenInUse || status == .authorizedAlways { + #if !targetEnvironment(simulator) + rootView.mapView.showsUserLocation = true + rootView.mapView.userTrackingMode = .follow + #endif + } + } +} diff --git a/QuickLocation/Section/Map/MapViewModel.swift b/QuickLocation/Section/Map/MapViewModel.swift new file mode 100644 index 00000000..c4ba4c87 --- /dev/null +++ b/QuickLocation/Section/Map/MapViewModel.swift @@ -0,0 +1,52 @@ +// +// MapViewModel.swift +// QuickLocation +// + +import Foundation +import RxSwift +import RxCocoa +import CoreLocation + +final class MapViewModel { + + struct Output { + var members: Observable<[CircleMember]> + var trackingMode: Observable + } + + let output: Output + + private let membersRelay = BehaviorRelay<[CircleMember]>(value: []) + private let trackingRelay = BehaviorRelay(value: true) + let selectedMember = PublishSubject() + + init() { + output = Output( + members: membersRelay.asObservable(), + trackingMode: trackingRelay.asObservable() + ) + } + + func loadMembers() { + membersRelay.accept(.mock) + } + + func toggleTracking() { + trackingRelay.accept(!trackingRelay.value) + } + + func selectMember(_ member: CircleMember) { + selectedMember.onNext(member) + } + + func currentUser() -> CircleMember? { + membersRelay.value.first { $0.isCurrentUser } + } + + #if !targetEnvironment(simulator) + func memberAnnotations() -> [MemberAnnotation] { + membersRelay.value.map { MemberAnnotation(member: $0) } + } + #endif +} diff --git a/QuickLocation/Section/Map/MemberAnnotation.swift b/QuickLocation/Section/Map/MemberAnnotation.swift new file mode 100644 index 00000000..a42cc569 --- /dev/null +++ b/QuickLocation/Section/Map/MemberAnnotation.swift @@ -0,0 +1,22 @@ +// +// MemberAnnotation.swift +// QuickLocation +// + +import Foundation +#if !targetEnvironment(simulator) +import MAMapKit + +final class MemberAnnotation: NSObject, MAAnnotation { + let member: CircleMember + + var coordinate: CLLocationCoordinate2D { member.coordinate } + var title: String? { member.name } + var subtitle: String? { member.address } + + init(member: CircleMember) { + self.member = member + super.init() + } +} +#endif diff --git a/QuickLocation/Section/Map/MemberAnnotationView.swift b/QuickLocation/Section/Map/MemberAnnotationView.swift new file mode 100644 index 00000000..ce9b2c73 --- /dev/null +++ b/QuickLocation/Section/Map/MemberAnnotationView.swift @@ -0,0 +1,166 @@ +// +// MemberAnnotationView.swift +// QuickLocation +// +// Created based on Lanhu design: 1.主页.-成员 +// + +import Foundation +#if !targetEnvironment(simulator) +import MAMapKit + +final class MemberAnnotationView: MAAnnotationView { + + // MARK: - Design Constants (50x50 avatar, 1pt border) + static let avatarOuterSize: CGFloat = 50 + static let avatarInnerSize: CGFloat = 48 + static let nameTagWidth: CGFloat = 60 + static let nameTagHeight: CGFloat = 20 + static let totalHeight: CGFloat = avatarOuterSize + 4 + nameTagHeight + + private let containerView: UIView = { + let v = UIView() + v.backgroundColor = .clear + return v + }() + + private let avatarOuterCircle: UIView = { + let v = UIView() + v.backgroundColor = .white + v.layer.cornerRadius = avatarOuterSize / 2 + v.layer.shadowColor = UIColor.black.withAlphaComponent(0.15).cgColor + v.layer.shadowOffset = CGSize(width: 0, height: 2) + v.layer.shadowRadius = 4 + v.layer.shadowOpacity = 1 + return v + }() + + private let avatarImageView: UIImageView = { + let iv = UIImageView() + iv.contentMode = .scaleAspectFill + iv.layer.cornerRadius = avatarInnerSize / 2 + iv.layer.borderWidth = 1 + iv.layer.borderColor = UIColor.white.cgColor + iv.clipsToBounds = true + iv.backgroundColor = UIColor(hexStr: "#E0E0E0") + return iv + }() + + private lazy var nameTagView: UIView = { + let v = UIView() + v.backgroundColor = .white + v.layer.cornerRadius = 4 + v.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor + v.layer.shadowOffset = CGSize(width: 0, height: 1) + v.layer.shadowRadius = 2 + v.layer.shadowOpacity = 1 + return v + }() + + private lazy var nameLabel: UILabel = { + let l = UILabel() + l.font = UIFont(name: "PingFangSC-Medium", size: 11) + ?? UIFont.systemFont(ofSize: 11, weight: .medium) + l.textColor = UIColor(hexStr: "#0F2846") + l.textAlignment = .center + l.lineBreakMode = .byTruncatingTail + return l + }() + + // MARK: - Heading indicator + private var headingLayer: CAShapeLayer? + + // MARK: - Init + override init!(annotation: MAAnnotation!, reuseIdentifier: String!) { + super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) + setupUI() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setupUI() { + canShowCallout = false + isEnabled = true + + bounds = CGRect(x: 0, y: 0, width: Self.nameTagWidth, height: Self.totalHeight) + centerOffset = CGPoint(x: 0, y: -Self.totalHeight / 2) + + addSubview(containerView) + containerView.frame = bounds + + containerView.addSubview(avatarOuterCircle) + avatarOuterCircle.frame = CGRect( + x: (Self.nameTagWidth - Self.avatarOuterSize) / 2, y: 0, + width: Self.avatarOuterSize, height: Self.avatarOuterSize + ) + + avatarOuterCircle.addSubview(avatarImageView) + avatarImageView.frame = CGRect( + x: (Self.avatarOuterSize - Self.avatarInnerSize) / 2, + y: (Self.avatarOuterSize - Self.avatarInnerSize) / 2, + width: Self.avatarInnerSize, height: Self.avatarInnerSize + ) + + containerView.addSubview(nameTagView) + nameTagView.frame = CGRect( + x: 0, y: Self.avatarOuterSize + 4, + width: Self.nameTagWidth, height: Self.nameTagHeight + ) + + nameTagView.addSubview(nameLabel) + nameLabel.frame = nameTagView.bounds.insetBy(dx: 4, dy: 0) + } + + // MARK: - Configure + func configure(with member: CircleMember) { + avatarImageView.image = UIImage(named: member.avatar) + avatarImageView.backgroundColor = member.avatar.isEmpty ? UIColor(hexStr: "#E0E0E0") : .clear + nameLabel.text = member.name + + if member.isCurrentUser { + nameLabel.textColor = UIColor(hexStr: "#16B3FF") + addHeadingIndicator(heading: member.heading) + } else { + nameLabel.textColor = UIColor(hexStr: "#0F2846") + headingLayer?.removeFromSuperlayer() + headingLayer = nil + } + } + + // MARK: - Heading + func updateHeading(_ heading: Double) { + headingLayer?.removeFromSuperlayer() + addHeadingIndicator(heading: heading) + } + + /// Draw a 60° semi-transparent blue fan centered on the avatar, pointing in the heading direction. + private func addHeadingIndicator(heading: Double) { + headingLayer?.removeFromSuperlayer() + + let center = CGPoint(x: Self.nameTagWidth / 2, y: Self.avatarOuterSize / 2) + let radius: CGFloat = Self.avatarOuterSize / 2 + 16 + + let halfFan = 30.0 * .pi / 180 + let centerAngle = CGFloat(heading) * .pi / 180 - .pi / 2 + let startAngle = centerAngle - halfFan + let endAngle = centerAngle + halfFan + + let path = UIBezierPath() + path.move(to: center) + path.addArc(withCenter: center, radius: radius, + startAngle: startAngle, endAngle: endAngle, + clockwise: true) + path.close() + + let shapeLayer = CAShapeLayer() + shapeLayer.path = path.cgPath + shapeLayer.fillColor = UIColor(hexStr: "#16B3FF").withAlphaComponent(0.25).cgColor + shapeLayer.strokeColor = UIColor(hexStr: "#16B3FF").withAlphaComponent(0.4).cgColor + shapeLayer.lineWidth = 1 + containerView.layer.insertSublayer(shapeLayer, at: 0) + headingLayer = shapeLayer + } +} +#endif diff --git a/QuickLocation/Section/Mine/MineView.swift b/QuickLocation/Section/Mine/MineView.swift new file mode 100644 index 00000000..9c2525f0 --- /dev/null +++ b/QuickLocation/Section/Mine/MineView.swift @@ -0,0 +1,339 @@ +// +// MineView.swift +// QuickLocation +// +// Created based on Lanhu design: 我的·版本6 +// + +import UIKit +import RxSwift +import RxCocoa + +final class MineView: UIView { + + var disposeBag = DisposeBag() + + // MARK: - Design Constants (iOS points, from Lanhu 版本6 @2x) + private let headerHeight: CGFloat = 160 + private let avatarSize: CGFloat = 64 + private let editBtnSize: CGFloat = 30 + private let copyIconSize: CGFloat = 14 + + private let vipCardHeight: CGFloat = 90 + + private let settingsRowHeight: CGFloat = 52 + + // MARK: - Colors + private let titleColor = UIColor(hexStr: "#1A1A1A") + private let subtitleColor = UIColor(hexStr: "#767676") + private let vipBtnTextColor = UIColor(hexStr: "#00343B") + + private func setupRx() { + avatarImageView.rx.tapGesture.subscribe { _ in + AppRouter.push(Route.login) + }.disposed(by: disposeBag) + } + + // MARK: - UI Components + private lazy var headerBgImageView: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Mine/header_bg") + iv.contentMode = .scaleAspectFill + iv.clipsToBounds = true + return iv + }() + + lazy var avatarImageView: UIImageView = { + let iv = UIImageView() + iv.isUserInteractionEnabled = true + iv.contentMode = .scaleAspectFill + iv.layer.cornerRadius = avatarSize / 2 + iv.layer.borderWidth = 2 + iv.layer.borderColor = UIColor.white.cgColor + iv.clipsToBounds = true + iv.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor + iv.layer.shadowOffset = .zero + iv.layer.shadowRadius = 2 + iv.layer.shadowOpacity = 1 + iv.backgroundColor = UIColor(hexStr: "#E0E0E0") + iv.image = UIImage(named: "Mine/default_avatar") + return iv + }() + + lazy var nameLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 16, weight: .heavy) + label.textColor = titleColor + label.text = "肖战大王叫我来巡山" + return label + }() + + lazy var editButton: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Mine/edit"), for: .normal) + btn.backgroundColor = .clear + return btn + }() + + lazy var idLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 14, weight: .medium) + label.textColor = subtitleColor + label.text = "ID:1234567" + return label + }() + + lazy var copyButton: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Mine/copy"), for: .normal) + btn.backgroundColor = .clear + return btn + }() + + // VIP Card + private lazy var vipCardView: UIView = { + let view = UIView() + view.layer.cornerRadius = 16 + view.clipsToBounds = true + return view + }() + + private lazy var vipCardBgImageView: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Mine/vip_card") + iv.contentMode = .scaleToFill + return iv + }() + + lazy var vipActivateButton: UIButton = { + let btn = UIButton(type: .custom) + btn.backgroundColor = .clear + return btn + }() + + // Profile transition background (100pt section below VIP card) + private lazy var profileBgImageView: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(named: "Mine/profile_bg") + iv.contentMode = .scaleToFill + return iv + }() + + private lazy var bottomFillView: UIView = { + let view = UIView() + view.backgroundColor = UIColor(hexStr: "#F5FBFB") + return view + }() + + // Settings Card + private lazy var settingsCardView: UIView = { + let view = UIView() + view.backgroundColor = .white + view.layer.cornerRadius = 12 + view.layer.shadowColor = UIColor(red: 0.898, green: 0.898, blue: 0.898, alpha: 0.3).cgColor + view.layer.shadowOffset = .zero + view.layer.shadowRadius = 4 + view.layer.shadowOpacity = 1 + return view + }() + + lazy var settingsTableView: UITableView = { + let tv = UITableView(frame: .zero, style: .plain) + tv.backgroundColor = .clear + tv.isScrollEnabled = false + tv.separatorStyle = .none + tv.register(MineMenuCell.self) + tv.rowHeight = settingsRowHeight + tv.estimatedRowHeight = settingsRowHeight + return tv + }() + + // MARK: - Callbacks + var onMenuTap: ((Int) -> Void)? + + // MARK: - Init + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupLayout() + setupRx() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + // MARK: - Setup + private func setupUI() { + backgroundColor = .white + + addSubview(headerBgImageView) + addSubview(avatarImageView) + addSubview(nameLabel) + addSubview(editButton) + addSubview(idLabel) + addSubview(copyButton) + + addSubview(vipCardView) + vipCardView.addSubview(vipCardBgImageView) + vipCardView.addSubview(vipActivateButton) + + addSubview(profileBgImageView) + addSubview(bottomFillView) + addSubview(settingsCardView) + settingsCardView.addSubview(settingsTableView) + } + + private func setupLayout() { + // Header + headerBgImageView.layoutChain + .top().left().right() + .height(headerHeight) + + // Avatar + avatarImageView.layoutChain + .top(kStatusBarHeight + 44) + .left(32) + .size(CGSize(width: avatarSize, height: avatarSize)) + + // Name + nameLabel.layoutChain + .leftToRightOfView(avatarImageView, offset: 20) + .topToView(avatarImageView, offset: 8) + + // Edit button + editButton.layoutChain + .right(16) + .centerY(nameLabel) + .size(CGSize(width: editBtnSize, height: editBtnSize)) + + // ID + idLabel.layoutChain + .leftToRightOfView(avatarImageView, offset: 20) + .topToBottomOfView(nameLabel, offset: 4) + + // Copy button + copyButton.layoutChain + .leftToRightOfView(idLabel, offset: 4) + .centerY(idLabel) + .size(CGSize(width: copyIconSize, height: copyIconSize)) + + // VIP Card + vipCardView.layoutChain + .topToBottomOfView(avatarImageView, offset: 28) + .left(16).right(16) + .height(vipCardHeight) + + vipCardBgImageView.layoutChain + .edges() + + vipActivateButton.layoutChain + .right(0).centerY() + .width(86).height(28) + + // Profile transition background (100pt, overlaps VIP card bottom half) + profileBgImageView.layoutChain + .topToView(vipCardView, offset: 32) + .left().right() + .height(100) + + // Fill below profile transition + bottomFillView.layoutChain + .topToBottomOfView(profileBgImageView) + .left().right().bottom() + + // Settings Card (fixed height, not stretched) + settingsCardView.layoutChain + .topToBottomOfView(vipCardView, offset: 20) + .left(16).right(16) + .height(312) + + settingsTableView.layoutChain + .edges() + } +} + +// MARK: - MineMenuCell +final class MineMenuCell: UITableViewCell { + + func configure(_ model: MineMenuItem) { + iconImageView.image = UIImage(named: model.icon) + titleLabel.text = model.title + } + + private func setupSubviews() { + contentView.addSubview(iconImageView) + contentView.addSubview(titleLabel) + contentView.addSubview(arrowImageView) + contentView.addSubview(dividerLine) + + iconImageView.layoutChain + .left(14).centerY() + .size(CGSize(width: 24, height: 24)) + + titleLabel.layoutChain + .leftToRightOfView(iconImageView, offset: 8) + .centerY() + + arrowImageView.layoutChain + .right(14).centerY() + .size(CGSize(width: 18, height: 18)) + + dividerLine.layoutChain + .left(14).right().bottom() + .height(0.5) + } + + var showDivider: Bool = true { + didSet { dividerLine.isHidden = !showDivider } + } + + private let iconImageView: UIImageView = { + let iv = UIImageView() + iv.contentMode = .scaleAspectFit + return iv + }() + + private let titleLabel: UILabel = { + let label = UILabel() + label.font = UIFont(name: "PingFangSC-Medium", size: 14) + ?? UIFont.systemFont(ofSize: 14, weight: .medium) + label.textColor = UIColor(hexStr: "#1A1A1A") + return label + }() + + private let arrowImageView: UIImageView = { + let iv = UIImageView() + iv.contentMode = .scaleAspectFit + iv.image = UIImage(named: "Mine/arrow_right") + return iv + }() + + private let dividerLine: UIView = { + let view = UIView() + view.backgroundColor = UIColor(hexStr: "#EDEDED") + return view + }() + + override init(style: CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + backgroundColor = .clear + selectionStyle = .none + setupSubviews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } +} diff --git a/QuickLocation/Section/Mine/MineViewController.swift b/QuickLocation/Section/Mine/MineViewController.swift new file mode 100644 index 00000000..271d274f --- /dev/null +++ b/QuickLocation/Section/Mine/MineViewController.swift @@ -0,0 +1,128 @@ +// +// MineViewController.swift +// QuickLocation +// +// Created based on Lanhu design: 我的 +// + +import UIKit +import RxSwift +import RxCocoa +import RxDataSources + +final class MineViewController: BaseViewController { + + override var isNavigationBarHidden: Bool { true } + override var preferredStatusBarStyle: UIStatusBarStyle { .default } + + // MARK: - Properties + fileprivate var rootView: MineView! + + private var tableView: UITableView { + rootView.settingsTableView + } + + private let viewModel = MineViewModel() + + // MARK: - Lifecycle + override func loadView() { + rootView = MineView(frame: UIScreen.main.bounds) + view = rootView + } + + override func viewDidLoad() { + super.viewDidLoad() + bindViewModel() + reactiveAction() + + viewModel.loadMenuData() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + rootView.avatarImageView.dl.setImage(with: AppContextManager.shared.avater) + rootView.nameLabel.text = AppContextManager.shared.name + rootView.idLabel.text = "ID:" + AppContextManager.shared.userId + } + + // MARK: - Bindings + private func bindViewModel() { + viewModel.output.sectionedItems + .bind(to: tableView.rx.items(dataSource: dataSource)) + .disposed(by: disposeBag) + + tableView.rx.modelSelected(MineMenuItem.self) + .subscribe(viewModel.cellAction.inputs) + .disposed(by: disposeBag) + + viewModel.userName + .bind(to: rootView.nameLabel.rx.text) + .disposed(by: disposeBag) + + viewModel.userID + .bind(to: rootView.idLabel.rx.text) + .disposed(by: disposeBag) + } + + private func reactiveAction() { + rootView.vipActivateButton.rx.tap + .subscribe(onNext: { [weak self] in + // TODO: Navigate to VIP activation + }) + .disposed(by: disposeBag) + + rootView.editButton.rx.tap + .subscribe(onNext: { [weak self] in + // TODO: Navigate to edit profile + }) + .disposed(by: disposeBag) + + rootView.copyButton.rx.tap + .subscribe(onNext: { [weak self] in + guard let id = self?.rootView.idLabel.text else { return } + UIPasteboard.general.string = id.replacingOccurrences(of: "ID:", with: "") + DLToast.showSuccess(text: "已复制") + }) + .disposed(by: disposeBag) + + rootView.onMenuTap = { [weak self] index in + self?.handleMenuTap(at: index) + } + } + + // MARK: - UITableViewDataSource + lazy private var dataSource: RxTableViewSectionedReloadDataSource = { + return RxTableViewSectionedReloadDataSource( + configureCell: { (_, tableView, indexPath, model) in + let cell: MineMenuCell = tableView.dequeueReusableCell(for: indexPath) + cell.configure(model) + return cell + }) + }() + + private func handleMenuTap(at index: Int) { + switch index { + case 0: + // TODO: Account & security + break + case 1: + // TODO: Status setting + break + case 2: + // TODO: Emergency contact + break + case 3: + // TODO: Customer service + break + case 4: + // TODO: Privacy & agreement + break + case 5: + // TODO: Permission check + break + default: + break + } + } +} diff --git a/QuickLocation/Section/Mine/MineViewModel.swift b/QuickLocation/Section/Mine/MineViewModel.swift new file mode 100644 index 00000000..f6e746ac --- /dev/null +++ b/QuickLocation/Section/Mine/MineViewModel.swift @@ -0,0 +1,66 @@ +// +// MineViewModel.swift +// QuickLocation +// + +import Foundation +import RxSwift +import RxDataSources + +typealias MineListSectionModel = SectionModel + +class MineViewModel { + + struct Output { + var sectionedItems: Observable<[MineListSectionModel]> + } + + let output: Output + + private var disposeBag = DisposeBag() + private let sectionedItems = PublishSubject<[MineListSectionModel]>() + + let userAvatar = PublishSubject() + let userName = PublishSubject() + let userID = PublishSubject() + + let menuItems: [MineMenuItem] = [ + MineMenuItem(icon: "Mine/account_security", title: "账户与安全"), + MineMenuItem(icon: "Mine/status_setting", title: "状态设置"), + MineMenuItem(icon: "Mine/emergency_contact", title: "紧急联系人"), + MineMenuItem(icon: "Mine/customer_service", title: "在线客服"), + MineMenuItem(icon: "Mine/privacy_agreement", title: "隐私与协议"), + MineMenuItem(icon: "Mine/permission_check", title: "权限检测") + ] + + lazy var cellAction: Action = { this in + return Action { model in + + return .empty() + } + }(self) + + func loadMenuData() { + sectionedItems.onNext(menuItems.mapSection()) + } + + func loadUserInfo() { + // TODO: Load user info from API + } + + func performLogout() { + // TODO: Logout logic + } + + // MARK: - Init + init() { + output = Output( + sectionedItems: sectionedItems.asObservable() + ) + } +} + +struct MineMenuItem { + let icon: String + let title: String +} diff --git a/QuickLocation/Service/SystemService.swift b/QuickLocation/Service/SystemService.swift new file mode 100644 index 00000000..28327a55 --- /dev/null +++ b/QuickLocation/Service/SystemService.swift @@ -0,0 +1,28 @@ +// +// SystemService.swift +// QuickLocation +// +// Created by 八条 on 2026/5/26. +// + +import RxSwift +import Moya + +struct SystemService { + static let disposeBag = DisposeBag() + + /// 获取初始化数据 + static func userConfig() -> Observable { + return APIProvider.request(token: SystemAPI.userConfig.multiTarget, handle: false) + .map(UserConfigResponse.self) + .asObservable() + } + + /// 获取验证码 + static func sendSmsCode(phone: String) -> Observable { + let api = SystemAPI.sendCode(phone: phone).multiTarget + return APIProvider.request(token: api) + .map(SmsCodeResponse.self) + .asObservable() + } +} diff --git a/QuickLocation/Service/UserService.swift b/QuickLocation/Service/UserService.swift new file mode 100644 index 00000000..f837bf08 --- /dev/null +++ b/QuickLocation/Service/UserService.swift @@ -0,0 +1,36 @@ +// +// UserService.swift +// QuickLocation +// +// Created by 八条 on 2026/5/28. +// + +import RxSwift +import Moya + +struct UserService { + static let disposeBag = DisposeBag() + + /// 登录 + /// - Parameters: + /// - type: weixin、phone、apple、onekey、device、alipay + /// - bind:1绑定 2解绑 为空是登录 + static func login(type: String, + bind: String = "", + data: [String: Any]) -> Observable { + return APIProvider.request(token: UserAPI.login(type: type, + bind: bind, + data: data).multiTarget, + handle: false) + .map(UserLoginRespons.self) + .asObservable() + } + + /// 退出登录 + static func logout() -> Observable { + let api = UserAPI.logout.multiTarget + return APIProvider.request(token: api) + .map(ResponseModel.self) + .asObservable() + } +} diff --git a/QuickLocation/Tool/AutoLayout/AutoLayout+NSLayoutConstraint.swift b/QuickLocation/Tool/AutoLayout/AutoLayout+NSLayoutConstraint.swift new file mode 100644 index 00000000..d59ea968 --- /dev/null +++ b/QuickLocation/Tool/AutoLayout/AutoLayout+NSLayoutConstraint.swift @@ -0,0 +1,26 @@ +// +// File.swift +// +// +// Created by Johnhao on 2022/1/18. +// + +import UIKit + +extension NSLayoutConstraint { + enum Key { + internal static var originalConstraint = "originalConstraint" + } + + /// 原来的约束值 + var jh_originalConstraint: CGFloat { + set { + objc_setAssociatedObject(self, &Key.originalConstraint, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, &Key.originalConstraint) as? CGFloat ?? 0 + } + } + + +} diff --git a/QuickLocation/Tool/AutoLayout/AutoLayout+UIView.swift b/QuickLocation/Tool/AutoLayout/AutoLayout+UIView.swift new file mode 100644 index 00000000..d43beaa7 --- /dev/null +++ b/QuickLocation/Tool/AutoLayout/AutoLayout+UIView.swift @@ -0,0 +1,510 @@ +// +// AutoLayout_UIView.swift +// AutoLayoutSwiftDemo +// +// Created by Johnhao on 2022/1/6. +// + +import UIKit + +// MARK: - AutoLayout +extension UIView { + // MARK: - Private + private enum Key { + /// 存储约束key + internal static var lastConstraint = "lastConstraint" + /// 存储约束key + internal static var constraints = "constraints" + /// jhLayoutChain + internal static var jhLayoutChain = "jhLayoutChain" + /// collapsed + internal static var collapsed = "collapsed" + /// autoCollapsed + internal static var autoCollapse = "autoCollapse" + /// hiddenCollapsed + internal static var hiddenCollapse = "hiddenCollapse" + } + + /// 所有的约束 + private var jh_allConstraints: [NSLayoutConstraint] { + get { + jh_layoutConstraints.values.compactMap { $0 } + } + } + + /// 所有约束key-value + private var jh_layoutConstraints: [String: NSLayoutConstraint] { + get { + guard let constraints = objc_getAssociatedObject(self, &Key.constraints) as? [String: NSLayoutConstraint] else { + + let constraints = [String: NSLayoutConstraint]() + objc_setAssociatedObject(self, &Key.constraints, constraints, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return constraints + } + return constraints + } + + set { + objc_setAssociatedObject(self, &Key.constraints, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + @discardableResult + private func jh_constrain(attribute: NSLayoutConstraint.Attribute, + toSuperView: UIView?, + constant: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + var offset = constant + var new_relation = relation + if attribute == .bottom || attribute == .right || attribute == .trailing { + offset = -constant + if relation == .lessThanOrEqual { + new_relation = .greaterThanOrEqual + } else if relation == .greaterThanOrEqual { + new_relation = .lessThanOrEqual + } + } + return jh_constrain(attribute: attribute, + toAttribute: attribute, + otherView: toSuperView, + multiplier: 1.0, + constant: offset, + relation: new_relation) + } + + @discardableResult + private func jh_constrain(attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + otherView: UIView?, + multiplier: CGFloat, + constant: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + self.translatesAutoresizingMaskIntoConstraints = false + + let layoutKey = "\(attribute.rawValue)-\(relation.rawValue)-\((otherView?.hash ?? 0))-\(toAttribute.rawValue)-\(multiplier)" + // 判断是否存在相同约束 + guard let constraint = self.jh_layoutConstraints[layoutKey] else { + // 不存在就新建 + let constraint = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: otherView, attribute: toAttribute, multiplier: multiplier, constant: constant) + self.jh_layoutConstraints[layoutKey] = constraint + self.jh_lastConstraint = constraint + constraint.isActive = true + return constraint + } + // 存在就更新 + constraint.constant = constant + self.jh_lastConstraint = constraint + constraint.isActive = true + return constraint + } + +} + +// MARK: - Public +extension UIView { + @discardableResult + public func jh_constrainAttribute(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + of otherView: UIView) -> NSLayoutConstraint { + jh_constrainAttribute(attribute, + toAttribute: toAttribute, + of: otherView, + offset: 1.0) + } + + @discardableResult + public func jh_constrainAttribute(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + of otherView: UIView, + offset: CGFloat) -> NSLayoutConstraint { + jh_constrainAttribute(attribute, + toAttribute: toAttribute, + of: otherView, + offset: offset, + relation: .equal) + } + + @discardableResult + public func jh_constrainAttribute(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + of otherView: UIView?, + offset: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrain(attribute: attribute, + toAttribute: toAttribute, + otherView: otherView, + multiplier: 1.0, + constant: offset, + relation: relation) + } + + @discardableResult + public func jh_constrainAttribute(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + of otherView: UIView, + multiplier: CGFloat) -> NSLayoutConstraint { + jh_constrainAttribute(attribute, + toAttribute: toAttribute, + of: otherView, + multiplier: multiplier, + relation: .equal) + } + + @discardableResult + public func jh_constrainAttribute(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + of otherView: UIView, + multiplier: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrain(attribute: attribute, + toAttribute: toAttribute, + otherView: otherView, + multiplier: multiplier, + constant: 0.0, + relation: relation) + } + + @discardableResult + public func jh_constraint(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + otherView: UIView?, + offset: CGFloat, + multiplier: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrain(attribute: attribute, toAttribute: toAttribute, otherView: otherView, multiplier: multiplier, constant: offset, relation: relation) + } + +} + +// MARK: - Constraint +extension UIView { + + /// 最新一条约束 + public var jh_lastConstraint: NSLayoutConstraint? { + set { + objc_setAssociatedObject(self, &Key.lastConstraint, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + get { + objc_getAssociatedObject(self, &Key.lastConstraint) as? NSLayoutConstraint + } + } + + + + public func jh_constraint(_ attribute: NSLayoutConstraint.Attribute, + toAttribute: NSLayoutConstraint.Attribute, + otherView: UIView?, + multiplier: CGFloat = 1.0, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint? { + let layoutKey = "\(attribute.rawValue)-\(relation.rawValue)-\((otherView?.hash ?? 0))-\(toAttribute.rawValue)-\(multiplier)" + return jh_layoutConstraints[layoutKey] + } +} + +// MARK: - All +extension UIView { + /// 移除所有约束 + public func jh_removeAllConstraints() { + NSLayoutConstraint.deactivate(jh_allConstraints) + jh_layoutConstraints.removeAll() + translatesAutoresizingMaskIntoConstraints = true + jh_lastConstraint = nil + } +} + +// MARK: - Compression +extension UIView { + /// 抗水平方向压缩 + public var jh_compressionHorizontal: UILayoutPriority { + get { + contentCompressionResistancePriority(for: .horizontal) + } + + set { + setContentCompressionResistancePriority(newValue, for: .horizontal) + } + } + + /// 抗垂直方向压缩 + public var jh_compressionVertical: UILayoutPriority { + get { + contentCompressionResistancePriority(for: .vertical) + } + + set { + setContentCompressionResistancePriority(newValue, for: .vertical) + } + } + + /// 抗水平方向拉伸 + public var jh_huggingHorizontal: UILayoutPriority { + get { + contentHuggingPriority(for: .horizontal) + } + + set { + setContentHuggingPriority(newValue, for: .horizontal) + } + } + + /// 抗垂直方向拉伸 + public var jh_huggingVertical: UILayoutPriority { + get { + contentHuggingPriority(for: .vertical) + } + + set { + setContentHuggingPriority(newValue, for: .vertical) + } + } +} + +// MARK: - Collapse +extension UIView { + /// 设置视图是否伸缩,默认false,true时常量值为0,false时常量值为原始值 + public var jh_collapsed: Bool { + set { + jh_allConstraints.forEach { + if newValue { + $0.constant = 0 + } else { + $0.constant = $0.jh_originalConstraint + } + } + objc_setAssociatedObject(self, &Key.collapsed, newValue, .OBJC_ASSOCIATION_ASSIGN) + } + get { + objc_getAssociatedObject(self, &Key.collapsed) as? Bool ?? false + } + } + /// 设置视图是否自动收缩,如image为nil,text为nil、@""时自动收缩,默认false + public var jh_autoCollapse: Bool { + set { + objc_setAssociatedObject(self, &Key.autoCollapse, newValue, .OBJC_ASSOCIATION_ASSIGN) + } + + get { + objc_getAssociatedObject(self, &Key.autoCollapse) as? Bool ?? false + } + } + /// 设置视图是否隐藏时自动收缩、显示时自动展开,默认false + public var jh_hiddenCollapse: Bool { + set { + objc_setAssociatedObject(self, &Key.hiddenCollapse, newValue, .OBJC_ASSOCIATION_ASSIGN) + } + + get { + objc_getAssociatedObject(self, &Key.hiddenCollapse) as? Bool ?? false + } + } +} + +// MARK: - Axis +extension UIView { + @discardableResult + public func jh_alignCenterToSuperView(with offset: CGPoint = .zero) -> [NSLayoutConstraint] { + var constrints = [NSLayoutConstraint]() + constrints.append(jh_alignAxisToSuperView(.centerX, withOffset: offset.x)) + constrints.append(jh_alignAxisToSuperView(.centerY, withOffset: offset.y)) + return constrints + } + + @discardableResult + public func jh_alignAxisToSuperView(_ axis: NSLayoutConstraint.Attribute, + withOffset: CGFloat = 0) -> NSLayoutConstraint { + jh_constrain(attribute: axis, toSuperView: self.superview, constant: withOffset, relation: .equal) + } + + @discardableResult + public func jh_alignAxis(_ axis: NSLayoutConstraint.Attribute, + to otherView: UIView, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0) -> NSLayoutConstraint { + jh_constrain(attribute: axis, toAttribute: axis, otherView: otherView, multiplier: multiplier, constant: offset, relation: .equal) + } +} + +// MARK: - Edge +extension UIView { + @discardableResult + public func jh_pinEdgesToSuperView() -> [NSLayoutConstraint] { + jh_pinEdgesToSuperView(.zero) + } + + @discardableResult + public func jh_pinEdgesToSuperView(_ insets: UIEdgeInsets) -> [NSLayoutConstraint] { + var constraints = [NSLayoutConstraint]() + constraints.append(jh_pinEdgeToSuperView(.top, inset: insets.top)) + constraints.append(jh_pinEdgeToSuperView(.bottom, inset: insets.bottom)) + constraints.append(jh_pinEdgeToSuperView(.leading, inset: insets.left)) + constraints.append(jh_pinEdgeToSuperView(.trailing, inset: insets.right)) + return constraints + } + + @discardableResult + public func jh_pinEdgesToSuperView(_ insets: UIEdgeInsets, + excludingEdge: NSLayoutConstraint.Attribute) -> [NSLayoutConstraint] { + var constraints = [NSLayoutConstraint]() + if excludingEdge != .top { + constraints.append(jh_pinEdgeToSuperView(.top, inset: insets.top)) + } + if excludingEdge != .bottom { + constraints.append(jh_pinEdgeToSuperView(.bottom, inset: insets.bottom)) + } + if excludingEdge != .leading && excludingEdge != .left { + constraints.append(jh_pinEdgeToSuperView(.leading, inset: insets.left)) + } + if excludingEdge != .trailing && excludingEdge != .right { + constraints.append(jh_pinEdgeToSuperView(.trailing, inset: insets.right)) + } + return constraints + } + + @discardableResult + public func jh_pinEdgesToSuperViewHorizontal(inset: CGFloat = 0) -> [NSLayoutConstraint] { + var constraints = [NSLayoutConstraint]() + constraints.append(jh_pinEdgeToSuperView(.leading, inset: inset)) + constraints.append(jh_pinEdgeToSuperView(.trailing, inset: inset)) + return constraints + } + + @discardableResult + public func jh_pinEdgesToSuperViewVertical(inset: CGFloat = 0) -> [NSLayoutConstraint] { + var constraints = [NSLayoutConstraint]() + constraints.append(jh_pinEdgeToSuperView(.top, inset: inset)) + constraints.append(jh_pinEdgeToSuperView(.bottom, inset: inset)) + return constraints + } + + @discardableResult + public func jh_pinEdgeToSuperView(_ edge: NSLayoutConstraint.Attribute) -> NSLayoutConstraint { + jh_pinEdgeToSuperView(edge, + inset: 0.0) + } + + @discardableResult + public func jh_pinEdgeToSuperView(_ edge: NSLayoutConstraint.Attribute, inset: CGFloat) -> NSLayoutConstraint { + jh_pinEdgeToSuperView(edge, + inset: inset, + relation: .equal) + } + + @discardableResult + public func jh_pinEdgeToSuperView(_ edge: NSLayoutConstraint.Attribute, + inset: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrain(attribute: edge, + toSuperView: self.superview, + constant: inset, + relation: relation) + } + + @discardableResult + public func jh_pinEdge(_ edge: NSLayoutConstraint.Attribute, + toEdge: NSLayoutConstraint.Attribute, + of otherView: UIView) -> NSLayoutConstraint { + jh_pinEdge(edge, + toEdge: toEdge, + of: otherView, + offset: 0.0) + } + + @discardableResult + public func jh_pinEdge(_ edge: NSLayoutConstraint.Attribute, + toEdge: NSLayoutConstraint.Attribute, + of otherView: UIView, + offset: CGFloat) -> NSLayoutConstraint { + jh_pinEdge(edge, + toEdge: toEdge, + of: otherView, + offset: offset, + relation: .equal) + } + + @discardableResult + public func jh_pinEdge(_ edge: NSLayoutConstraint.Attribute, + toEdge: NSLayoutConstraint.Attribute, + of otherView: UIView, + offset: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrainAttribute(edge, + toAttribute: toEdge, + of: otherView, + offset: offset, + relation: relation) + } +} + +// MARK: - Dimension +extension UIView { + @discardableResult + public func jh_setDimensionToSize(_ size: CGSize) -> [NSLayoutConstraint] { + var constraints = [NSLayoutConstraint]() + constraints.append(jh_setDimension(.width, toSize: size.width)) + constraints.append(jh_setDimension(.height, toSize: size.height)) + return constraints + } + + @discardableResult + public func jh_setDimension(_ dimension: NSLayoutConstraint.Attribute, + toSize: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { + jh_constrain(attribute: dimension, toAttribute: .notAnAttribute, otherView: nil, multiplier: 1.0, constant: toSize, relation: relation) + } + + @discardableResult + public func jh_matchDimension(_ dimension: NSLayoutConstraint.Attribute, + toDimension: NSLayoutConstraint.Attribute, + ofView otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { + jh_constrainAttribute(dimension, toAttribute: toDimension, of: otherView, offset: offset, relation: relation) + } + + @discardableResult + public func jh_matchDimension(_ dimension: NSLayoutConstraint.Attribute, + toDimension: NSLayoutConstraint.Attribute, + multiplier: CGFloat = 1.0, + relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { + jh_constrainAttribute(dimension, toAttribute: toDimension, of: self, multiplier: multiplier, relation: relation) + } + + @discardableResult + public func jh_matchDimension(_ dimension: NSLayoutConstraint.Attribute, + toDimension: NSLayoutConstraint.Attribute, + ofView otherView: UIView, + multiplier: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrainAttribute(dimension, toAttribute: toDimension, of: otherView, multiplier: multiplier, relation: relation) + } + + @discardableResult + public func jh_matchDimension(_ dimension: NSLayoutConstraint.Attribute, + toDimension: NSLayoutConstraint.Attribute, + ofView otherView: UIView, + offset: CGFloat, + multiplier: CGFloat, + relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint { + jh_constrain(attribute: dimension, toAttribute: toDimension, otherView: otherView, multiplier: multiplier, constant: offset, relation: relation) + } + +} + +// MARK: - LayoutChain +extension UIView { + + public var layoutChain: AutoLayoutSwift { + get { + guard let layout = objc_getAssociatedObject(self, &Key.jhLayoutChain) as? AutoLayoutSwift else { + let layout = AutoLayoutSwift(view: self) + objc_setAssociatedObject(self, &Key.jhLayoutChain, layout, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return layout + } + return layout + } + } +} + + + diff --git a/QuickLocation/Tool/AutoLayout/AutoLayoutSwift.swift b/QuickLocation/Tool/AutoLayout/AutoLayoutSwift.swift new file mode 100644 index 00000000..c71d508b --- /dev/null +++ b/QuickLocation/Tool/AutoLayout/AutoLayoutSwift.swift @@ -0,0 +1,433 @@ +// +// AutoLayout.swift +// AutoLayoutSwiftDemo +// +// Created by Johnhao on 2022/1/17. +// + +import UIKit + +public class AutoLayoutSwift { + + private weak var view: UIView? + + public required init(view: UIView?) { + self.view = view + } + + @discardableResult + public func remake() -> AutoLayoutSwift { + view?.jh_removeAllConstraints() + return self + } +} + +// MARK: - Compression/Hugging +extension AutoLayoutSwift { + + + @discardableResult + public func compressionHorizontal(_ priority: UILayoutPriority) -> AutoLayoutSwift { + view?.jh_compressionHorizontal = priority + return self + } + + @discardableResult + public func compressionVertical(_ priority: UILayoutPriority) -> AutoLayoutSwift { + view?.jh_compressionVertical = priority + return self + } + + @discardableResult + public func huggingHorizontal(_ priority: UILayoutPriority) -> AutoLayoutSwift { + view?.jh_huggingHorizontal = priority + return self + } + + @discardableResult + public func huggingVertical(_ priority: UILayoutPriority) -> AutoLayoutSwift { + view?.jh_huggingVertical = priority + return self + } +} + +// MARK: - Collapse +extension AutoLayoutSwift { + + @discardableResult + public func collapsed(_ collapsed: Bool) -> AutoLayoutSwift { + view?.jh_collapsed = collapsed + return self + } + + @discardableResult + public func autoCollapse(_ isAuto: Bool) -> AutoLayoutSwift { + view?.jh_autoCollapse = isAuto + return self + } + + @discardableResult + public func hiddenCollapse(_ isHidden: Bool) -> AutoLayoutSwift { + return self + } +} + +// MARK: - Axis +extension AutoLayoutSwift { + @discardableResult + public func center() -> AutoLayoutSwift { + view?.jh_alignCenterToSuperView() + return self + } + + @discardableResult + public func centerX() -> AutoLayoutSwift { + view?.jh_alignAxisToSuperView(.centerX) + return self + } + + @discardableResult + public func centerY() -> AutoLayoutSwift { + view?.jh_alignAxisToSuperView(.centerY) + return self + } + + @discardableResult + public func center(_ otherView: UIView) -> AutoLayoutSwift { + view?.jh_alignAxis(.centerX, to: otherView) + view?.jh_alignAxis(.centerY, to: otherView) + return self + } + + @discardableResult + public func centerX(_ otherView: UIView, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0) -> AutoLayoutSwift { + view?.jh_alignAxis(.centerX, to: otherView, offset: offset, multiplier: multiplier) + return self + } + + @discardableResult + public func centerY(_ otherView: UIView, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0) -> AutoLayoutSwift { + view?.jh_alignAxis(.centerY, to: otherView, offset: offset, multiplier: multiplier) + return self + } +} + +// MARK: - Edge +extension AutoLayoutSwift { + + @discardableResult + public func edges(_ insets: UIEdgeInsets = UIEdgeInsets.zero) -> AutoLayoutSwift { + view?.jh_pinEdgesToSuperView(insets) + return self + } + + @discardableResult + public func edges(_ insets: UIEdgeInsets = .zero, excludingEdge: NSLayoutConstraint.Attribute) -> AutoLayoutSwift { + view?.jh_pinEdgesToSuperView(insets, excludingEdge: excludingEdge) + return self + } + + @discardableResult + public func edges(all: CGFloat) -> AutoLayoutSwift { + view?.jh_pinEdgesToSuperView(UIEdgeInsets(top: all, left: all, bottom: all, right: all)) + return self + } + + @discardableResult + public func edges(all: CGFloat, excludingEdge: NSLayoutConstraint.Attribute) -> AutoLayoutSwift { + view?.jh_pinEdgesToSuperView(UIEdgeInsets(top: all, left: all, bottom: all, right: all), excludingEdge: excludingEdge) + return self + } + + @discardableResult + public func edgesHorzontal(_ inset: CGFloat = 0) -> AutoLayoutSwift { + view?.jh_pinEdgesToSuperViewHorizontal(inset: inset) + return self + } + + @discardableResult + public func edgesVertical(_ inset: CGFloat = 0) -> AutoLayoutSwift { + view?.jh_pinEdgesToSuperViewVertical(inset: inset) + return self + } + + @discardableResult + public func top(_ inset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdgeToSuperView(.top, inset: inset, relation: relation) + return self + } + + @discardableResult + public func bottom(_ inset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdgeToSuperView(.bottom, inset: inset, relation: relation) + return self + } + + @discardableResult + public func left(_ inset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdgeToSuperView(.leading, inset: inset, relation: relation) + return self + } + + @discardableResult + public func leading(_ inset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdgeToSuperView(.leading, inset: inset, relation: relation) + return self + } + + @discardableResult + public func right(_ inset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdgeToSuperView(.trailing, inset: inset, relation: relation) + return self + } + + @discardableResult + public func trailing(_ inset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdgeToSuperView(.trailing, inset: inset, relation: relation) + return self + } + + @discardableResult + public func topToView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.top, toEdge: .top, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func bottomToView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.bottom, toEdge: .bottom, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func leftToView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.leading, toEdge: .leading, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func rightToView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.trailing, toEdge: .trailing, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func topToBottomOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.top, toEdge: .bottom, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func bottomToTopOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.bottom, toEdge: .top, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func leftToRightOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.leading, toEdge: .trailing, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func rightToLeftOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.trailing, toEdge: .leading, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func topToCenterYOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.top, toEdge: .centerY, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func bottomToCenterYOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.bottom, toEdge: .centerY, of: otherView, offset: -offset, relation: relation) + return self + } + + @discardableResult + public func leftToCenterXOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.leading, toEdge: .centerX, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func rightToCenterXOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.trailing, toEdge: .centerX, of: otherView, offset: -offset, relation: relation) + return self + } + + @discardableResult + public func centerXToRightOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.centerX, toEdge: .trailing, of: otherView, offset: offset, relation: relation) + return self + } + + @discardableResult + public func centerYToTopOfView(_ otherView: UIView, + offset: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_pinEdge(.centerY, toEdge: .top, of: otherView, offset: offset, relation: relation) + return self + } +} + +// MARK: - Baseline +extension AutoLayoutSwift { + @discardableResult + public func firstBaselineToView(_ otherView: UIView, + to attribute: NSLayoutConstraint.Attribute = .firstBaseline) -> AutoLayoutSwift { + view?.jh_constrainAttribute(.firstBaseline, toAttribute: attribute, of: otherView) + return self + } + + @discardableResult + public func lastBaselineToView(_ otherView: UIView, + to attribute: NSLayoutConstraint.Attribute = .lastBaseline) -> AutoLayoutSwift { + view?.jh_constrainAttribute(.lastBaseline, toAttribute: attribute, of: otherView) + return self + } + + @discardableResult + public func constrainAttribute(_ attribute: NSLayoutConstraint.Attribute, + otherView: UIView, + to otherAttribute: NSLayoutConstraint.Attribute, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_constraint(attribute, toAttribute: otherAttribute, otherView: otherView, offset: offset, multiplier: multiplier, relation: relation) + return self + } +} + +// MARK: - Dimension +extension AutoLayoutSwift { + + @discardableResult + public func size(_ size: CGSize) -> AutoLayoutSwift { + view?.jh_setDimensionToSize(size) + return self + } + + @discardableResult + public func width(_ width: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_setDimension(.width, toSize: width, relation: relation) + return self + } + + @discardableResult + public func height(_ height: CGFloat = 0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_setDimension(.height, toSize: height, relation: relation) + return self + } + + @discardableResult + public func widthToHeight(_ multipler: CGFloat, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_matchDimension(.width, toDimension: .height, multiplier: multipler, relation: relation) + return self + } + + @discardableResult + public func heightToWidth(_ multipler: CGFloat, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_matchDimension(.height, toDimension: .width, multiplier: multipler, relation: relation) + return self + } + + @discardableResult + public func sizeToView(_ otherView: UIView) -> AutoLayoutSwift { + view?.jh_matchDimension(.width, toDimension: .width, ofView: otherView) + view?.jh_matchDimension(.height, toDimension: .height, ofView: otherView) + return self + } + + + @discardableResult + public func widthToView(_ otherView: UIView, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_matchDimension(.width, toDimension: .width, ofView: otherView, offset: offset, multiplier: multiplier,relation: relation) + return self + } + + @discardableResult + public func heightToView(_ otherView: UIView, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_matchDimension(.height, toDimension: .height, ofView: otherView, offset: offset, multiplier: multiplier, relation: relation) + return self + } +} + + +// MARK: - Attribute +extension AutoLayoutSwift { + + @discardableResult + public func attribute(_ attribute: NSLayoutConstraint.Attribute, + to otherArribute: NSLayoutConstraint.Attribute, + of otherView: UIView, + offset: CGFloat = 0, + multiplier: CGFloat = 1.0, + relation: NSLayoutConstraint.Relation = .equal) -> AutoLayoutSwift { + view?.jh_constraint(attribute, toAttribute: otherArribute, otherView: otherView, offset: offset, multiplier: multiplier, relation: relation) + return self + } +} + +// MARK: - Constranit +extension AutoLayoutSwift { + + public var constraint: NSLayoutConstraint? { + view?.jh_lastConstraint + } + +// @discardableResult +// public func constraint(_ attribute: NSLayoutConstraint.Attribute, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint? { +// view?.jh_constrainAttribute(attribute, toAttribute: attribute, of: <#T##UIView#>) +// } + +} diff --git a/QuickLocation/Tool/Router/AppRouter.swift b/QuickLocation/Tool/Router/AppRouter.swift new file mode 100644 index 00000000..4ff733ad --- /dev/null +++ b/QuickLocation/Tool/Router/AppRouter.swift @@ -0,0 +1,218 @@ +// +// AppRouter.swift +// Alamofire +// +// Created by osell on 2023/2/7. +// + +import Foundation +import URLNavigator + +public typealias RouterParameter = [String : Any] +public typealias CustomHandlerFactory = (String, RouterParameter?) -> Bool +public typealias ContextHander = (String, RouterParameter) -> UIViewController? + +public protocol AppRouterProtocol: CustomStringConvertible { + func setupRegisterRouter() + func setupHandlerRouter() +} + +@objcMembers +public class AppRouter: NSObject { + + public static let shared = AppRouter() + + private let navigator: Navigator + + static var globalRouteHandler: CustomHandlerFactory? + + var rootViewController: UIViewController? { + return UIViewController.topMost + } + + var navigationController: UINavigationController? { + return UIViewController.topMost?.navigationController + } + + override init() { + self.navigator = Navigator() + super.init() + } + + public func setup() { + if let this = self as? AppRouterProtocol { + this.setupRegisterRouter() + this.setupHandlerRouter() + } + } +} + +// MARK: - Register/Handler +public extension AppRouter { + + /// 注册路由 + /// - Parameters: + /// - router: 路由 + /// - factory: ViewControllerFactory + class func register(_ router: RouterTarget, factory: @escaping ContextHander) { + AppRouter.shared.navigator.register(router.url) { _, values, context in + var values = values + if let userInfo = context as? RouterParameter { + values.merge(userInfo, uniquingKeysWith: { value1, value2 in value2 }) + } + return factory(router.url, values) + } + } + + /// 处理单个路由 + /// - Parameters: + /// - router: 路由 + /// - factory: URLOpenHandlerFactory + class func handle(_ router: RouterTarget, _ factory: @escaping CustomHandlerFactory) { + AppRouter.shared.navigator.handle(router.url) { _, values, context in + var values = values + if let userInfo = context as? RouterParameter { + values.merge(userInfo, uniquingKeysWith: { value1, value2 in value2 }) + } + return factory(router.url, values) + } + } + + /// 处理全局路由设置 + /// - Parameter handler: CustomHandlerFactory + class func globalRouteHandler(_ handler: CustomHandlerFactory?) { + AppRouter.globalRouteHandler = handler + } + + /// 是否注册过路由 + /// - Parameter url: 路由url + /// - Returns: true/false + class func isRegisterRouter(_ url: String, userInfo: RouterParameter?) -> Bool { + AppRouter.viewController(url, userInfo: userInfo) != nil + } + + class func viewController(_ url: String, userInfo: RouterParameter?) -> UIViewController? { + AppRouter.shared.navigator.viewController(for: url, context: userInfo) + } +} + +// MARK: - Push/Present +public extension AppRouter { + + /// Router RouteTarget Push + /// - Parameters: + /// - router: RouterTarget + /// - isHandler: 是否处理 + /// - userInfo: 参数 + /// - Returns: UIViewController + @discardableResult + class func push(_ router: RouterTarget, + userInfo: RouterParameter? = nil) -> UIViewController? { + var params = RouterParameter() + if let parameters = userInfo { + params = params.merging(parameters) { _, value2 in value2 } + } + guard AppRouter.globalRouteHandler?(router.url, params) == true else { + return nil + } + return AppRouter.shared.navigator.push(router.url, context: params) + } + + /// Router URLString Push + /// - Parameters: + /// - router: URL String + /// - isHandler: 是否处理 + /// - userInfo: 参数 + /// - Returns: UIViewController + @discardableResult + class func push(_ url: String, + userInfo: RouterParameter? = nil) -> UIViewController? { + let url = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" + guard let urlURL = URL(string: url) else { return nil } + var params = urlURL.queryParameters as RouterParameter + if let parameters = userInfo { + params = params.merging(parameters) { _, value2 in value2 } + } + guard AppRouter.globalRouteHandler?(url, params) == true else { + return nil + } + return AppRouter.shared.navigator.push(url, context: params) + } + + /// Pushes the view controller to the navigation controller stack. + /// + /// - note: It is not a good idea to use this method directly because this method requires all + /// parameters. This method eventually gets called when pushing a view controller, so + /// it's recommended to implement this method only for mocking. + @discardableResult + class func push(_ viewController: UIViewController, from: UINavigationControllerType? = nil, animated: Bool = true) -> UIViewController? { + return AppRouter.shared.navigator.push(viewController, from: from, animated: animated) + } + + /// Router RouteTarget Present + /// - Parameters: + /// - router: RouterTarget + /// - isHandler: 是否处理 + /// - userInfo: 参数 + /// - Returns: UIViewController + @discardableResult + class func present(_ router: RouterTarget, + userInfo: RouterParameter? = nil, + completion: (() -> Void)? = nil) -> UIViewController? { + + var params = RouterParameter() + if let parameters = userInfo { + params = params.merging(parameters) { _, value2 in value2 } + } + guard AppRouter.globalRouteHandler?(router.url, params) == true else { + return nil + } + return AppRouter.shared.navigator.present(router.url, context: params, completion: completion) + } + + /// Router URLString Present + /// - Parameters: + /// - router: URL String + /// - isHandler: 是否处理 + /// - userInfo: 参数 + /// - Returns: UIViewController + @discardableResult + class func present(_ url: String, + userInfo: RouterParameter? = nil, + completion: (() -> Void)? = nil) -> UIViewController? { + let url = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" + guard let urlURL = URL(string: url) else { return nil } + var params = urlURL.queryParameters as RouterParameter + if let parameters = userInfo { + params = params.merging(parameters) { _, value2 in value2 } + } + guard AppRouter.globalRouteHandler?(url, params) == true else { + return nil + } + return AppRouter.shared.navigator.present(url, context: params, completion: completion) + } + + /// Router URLString Present + /// - Parameters: + /// - viewController: viewController + /// - animated: + /// - completion: + /// - Returns: UIViewController + @discardableResult + class func present(_ viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) -> UIViewController? { + return AppRouter.shared.navigator.present(viewController, animated: animated, completion: completion) + } + + func popOrDismiss() { + if navigationController?.viewControllers.count == 1 && + navigationController?.presentingViewController != nil { + navigationController?.dismiss(animated: true, completion: nil) + } else { + navigationController?.popViewController(animated: true) + } + } + + func popToRoot() { + navigationController?.popToRootViewController(animated: true) + } +} diff --git a/QuickLocation/Tool/Router/RouterTarget.swift b/QuickLocation/Tool/Router/RouterTarget.swift new file mode 100644 index 00000000..5d42781f --- /dev/null +++ b/QuickLocation/Tool/Router/RouterTarget.swift @@ -0,0 +1,24 @@ +// +// RouterTarget.swift +// Alamofire +// +// Created by osell on 2023/2/7. +// + +import Foundation + +public protocol RouterTarget { + + var scheme: String { get } + + var name: String { get } + + var path: String { get } + + var url: String { get } + +} + +public extension RouterTarget { + var url: String { scheme + path } +} diff --git a/QuickLocation/UIKit/Alert/DLAlert.swift b/QuickLocation/UIKit/Alert/DLAlert.swift new file mode 100644 index 00000000..0c252757 --- /dev/null +++ b/QuickLocation/UIKit/Alert/DLAlert.swift @@ -0,0 +1,356 @@ +// +// DLAlert.swift +// Alamofire +// +// Created by osell on 2023/8/17. +// + +import UIKit + + +public class DLAlert { + + /// 显示Alert, subTitle是使用文本 + /// - Parameters: + /// - config: 配置信息 + /// - title: 标题 + /// - subTitle: 子标题 + /// - moreTitle: 更多按钮标题 + /// - moreAction: 更多按钮点击回调 + /// - defulatTitle: 默认按钮标题 + /// - defulatAction: 默认按钮点击回调 + public static func show(config: DLAlertConfig = DLAlertConfig(), + title: String?=nil, + subTitle: String?=nil, + content: String?=nil, + moreTitle: String?=nil, + moreAction: (() -> Void)?=nil, + defaultTitle: String, + defaultAction: (() -> Void)?=nil) { + guard let window = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first else { return } + if title?.isEmpty != false && subTitle?.isEmpty != false { return } + let view = DLAlertView(title: title, subtitle: subTitle, content:content, moreBtnTitle: moreTitle, defaultBtnTitle: defaultTitle, config: config) + view.defaultAction = defaultAction + view.moreAction = moreAction + view.show(on: window) + } + + /// 显示Alert, subTitle是使用富文本 + /// - Parameters: + /// - config: 配置信息 + /// - title: 标题 + /// - subTitle: 子标题,富文本 + /// - moreTitle: 更多按钮标题 + /// - moreAction: 更多按钮点击回调 + /// - defulatTitle: 默认按钮标题 + /// - defulatAction: 默认按钮点击回调 + public static func showAttributeText(config: DLAlertConfig = DLAlertConfig(), + title: String?=nil, + subtitle: NSAttributedString?=nil, + moreTitle: String?=nil, + moreAction: (() -> Void)?=nil, + defaultTitle: String, + defaultAction: (() -> Void)?=nil) { + guard let window = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first else { return } + let view = DLAlertView(title: title, subtitleAttribute: subtitle, moreBtnTitle: moreTitle, defaultBtnTitle: defaultTitle, config: config) + view.defaultAction = defaultAction + view.moreAction = moreAction + view.show(on: window) + } +} + +public class DLAlertConfig { + /// cover背景颜色 + public var coverBgColor: UIColor = .black.withAlphaComponent(0.5) + /// 内容背景颜色 + public var contentBgColor: UIColor = .white + /// 标题颜色 + public var titleColor: UIColor = ThemeManager.shared.color.titleColor + /// 子标题颜色 + public var subtitleColor: UIColor = ThemeManager.shared.color.titleColor + /// 内容颜色 + public var contentColor: UIColor = ThemeManager.shared.color.contentColor + /// 标题字体大小 + public var titleFont: UIFont = .systemFont(ofSize: 18, weight: .medium) + /// 子标题字体大小 + public var subtitleFont: UIFont = .systemFont(ofSize: 15, weight: .regular) + /// 内容 + public var contentFont: UIFont = .systemFont(ofSize: 12, weight: .regular) + public var moreBtnColor: UIColor = ThemeManager.shared.color.contentColor + public var defaultBtnColor: UIColor = .white + public var moreBtnBgColor: UIColor = .white + public var defaultBtnBgColor: UIColor = ThemeManager.shared.color.mainColor + public var moreBtnFont: UIFont = .systemFont(ofSize: 18, weight: .regular) + public var defaultBtnFont: UIFont = .systemFont(ofSize: 18, weight: .medium) + + public init() {} +} + +class DLAlertView: UIView { + + var defaultAction: (() -> Void)? + var moreAction: (() -> Void)? + + lazy var contentView: UIView = { + let view = UIView() + view.backgroundColor = config.contentBgColor + view.setCornerRadius(8) + return view + }() + + /// + lazy var titleLabel: UILabel = { + let label = UILabel() + label.font = config.titleFont + label.textColor = config.titleColor + label.text = title + label.numberOfLines = 0 + label.textAlignment = .center + return label + }() + + lazy var subtitleLabel: UILabel = { + let label = UILabel() + label.font = config.subtitleFont + label.textColor = config.subtitleColor + label.attributedText = subtitleAttribute ?? NSAttributedString(string: subtitle) + label.numberOfLines = 0 + label.textAlignment = .center + return label + }() + + lazy var contentLabel: UILabel = { + let label = UILabel() + label.font = config.contentFont + label.textColor = config.contentColor + label.text = content +// label.attributedText = subtitleAttribute ?? NSAttributedString(string: subtitle) + label.numberOfLines = 0 + label.textAlignment = .center + return label + }() + + /// + lazy var moreBtn: UIButton = { + let btn = UIButton() + btn.titleLabel?.font = config.moreBtnFont + btn.setTitle(moreBtnTitle, for: .normal) + btn.setTitleColor(config.moreBtnColor, for: .normal) + btn.setBackgroundColor(config.moreBtnBgColor, for: .normal) + btn.borderColor = ThemeManager.shared.color.contentColor + btn.borderWidth = 0.5 + btn.addTapGestrue { [weak self] _ in + self?.dismiss() + self?.moreAction?() + } + btn.cornerRadius = 18 + return btn + }() + + lazy var defaultBtn: UIButton = { + let btn = UIButton() + btn.titleLabel?.font = config.defaultBtnFont + btn.setTitle(defaultBtnTitle, for: .normal) + btn.setTitleColor(config.defaultBtnColor, for: .normal) + btn.setBackgroundColor(config.defaultBtnBgColor, for: .normal) + btn.addTapGestrue { [weak self] _ in + self?.dismiss() + self?.defaultAction?() + } + btn.cornerRadius = 18 + return btn + }() + + /// line + lazy var hLineView: UIView = { + let view = UIView() + view.backgroundColor = UIColor(hexStr: "#EEEEEE", alpha: 1.0) + return view + }() + + /// line + lazy var vLineView: UIView = { + let view = UIView() + view.backgroundColor = UIColor(hexStr: "#EEEEEE", alpha: 1.0) + return view + }() + + /// btnView + lazy var bottonView: UIStackView = { + let view = UIStackView(arrangedSubviews: [moreBtn, defaultBtn]) + view.axis = .horizontal + view.spacing = 16 + view.distribution = .fillEqually + view.alignment = .center + return view + }() + + var config: DLAlertConfig + var title: String = "" + var subtitle: String = "" + var subtitleAttribute: NSAttributedString? + var content: String = "" + var contentAttribute: NSAttributedString? + var moreBtnTitle: String = "" + var defaultBtnTitle: String = "" + fileprivate weak var viewForPresent: UIView? + + init(title: String?=nil, + subtitle: String?=nil, + content: String?=nil, + moreBtnTitle: String?=nil, + defaultBtnTitle: String, + config: DLAlertConfig = DLAlertConfig()) { + self.config = config + self.title = title ?? "" + self.subtitle = subtitle ?? "" + self.content = content ?? "" + self.moreBtnTitle = moreBtnTitle ?? "" + self.defaultBtnTitle = defaultBtnTitle + super.init(frame: .zero) + setupSubViews() + } + + init(title: String?=nil, + subtitleAttribute: NSAttributedString?=nil, + contentAttribute: NSAttributedString?=nil, + moreBtnTitle: String?=nil, + defaultBtnTitle: String, + config: DLAlertConfig = DLAlertConfig()) { + self.config = config + self.title = title ?? "" + self.subtitleAttribute = subtitleAttribute + self.contentAttribute = contentAttribute + self.moreBtnTitle = moreBtnTitle ?? "" + self.defaultBtnTitle = defaultBtnTitle + super.init(frame: .zero) + setupSubViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func setupSubViews() { + addSubview(contentView) + contentView.layoutChain + .centerX() + .centerY(self, offset: -kScreenWidth * 0.1) + .left(48, relation: .greaterThanOrEqual) + .right(48, relation: .greaterThanOrEqual) + .top(kNaviHeight, relation: .greaterThanOrEqual) + .bottom(kNaviHeight, relation: .greaterThanOrEqual) + .width(280, relation: .greaterThanOrEqual) + + var preView: UIView? + if !title.isEmpty { + // 标题 + contentView.addSubview(titleLabel) + titleLabel.layoutChain + .top(18) + .edgesHorzontal(20) + preView = titleLabel + } + + if !subtitle.isEmpty || subtitleAttribute != nil { + // 子标题 + contentView.addSubview(subtitleLabel) + subtitleLabel.layoutChain + .edgesHorzontal(20) + + if let preView = preView { + subtitleLabel.layoutChain + .topToBottomOfView(preView, offset: 10) + } else { + subtitleLabel.layoutChain + .top(20) + } + preView = subtitleLabel + } + + if !content.isEmpty { + contentView.addSubview(contentLabel) + contentLabel.layoutChain + .edgesHorzontal(20) + + if let preView = preView { + contentLabel.layoutChain + .topToBottomOfView(preView, offset: 10) + } else { + contentLabel.layoutChain + .top(20) + } + preView = contentLabel + } + + // 底部按钮 + moreBtn.isHidden = moreBtnTitle.isEmpty + contentView.addSubview(bottonView) + bottonView.layoutChain + .edgesHorzontal(12) + .height(50) + .bottom(5) + + if let preView = preView { + bottonView.layoutChain + .topToBottomOfView(preView, offset: 20) + } else { + bottonView.layoutChain + .top(20) + } + + defaultBtn.layoutChain + .height(36) + + moreBtn.layoutChain + .height(36) + +// contentView.addSubview(hLineView) +// hLineView.layoutChain +// .edgesHorzontal() +// .bottomToTopOfView(bottonView) +// .height(0.5) +// +// if !moreBtnTitle.isEmpty { +// contentView.addSubview(vLineView) +// vLineView.layoutChain +// .centerX() +// .topToView(bottonView) +// .bottomToView(bottonView) +// .width(0.5) +// } + + } + +} + +extension DLAlertView { + + func show(on view: UIView) { + viewForPresent = view + guard let viewForPresent = viewForPresent else { return } + self.backgroundColor = .clear + viewForPresent.addSubview(self) + self.layoutChain + .edges() + alpha = 0 + sizeToFit() + contentView.center = .init(x: viewForPresent.frame.midX, y: viewForPresent.frame.midY) + contentView.transform = transform.scaledBy(x: 0.8, y: 0.8) + UIView.animate(withDuration: 0.25) { + self.alpha = 1 + self.contentView.transform = CGAffineTransform.identity + self.backgroundColor = self.config.coverBgColor + } completion: { _ in + } + } + + func dismiss() { + UIView.animate(withDuration: 0.25) { + self.alpha = 0 + self.contentView.transform = self.contentView.transform.scaledBy(x: 0.2, y: 0.2) + } completion: { _ in + self.removeFromSuperview() + } + } +} diff --git a/QuickLocation/UIKit/Alert/DLToast.swift b/QuickLocation/UIKit/Alert/DLToast.swift new file mode 100644 index 00000000..c0ff2835 --- /dev/null +++ b/QuickLocation/UIKit/Alert/DLToast.swift @@ -0,0 +1,482 @@ +// +// DLToast.swift +// DLSDK +// +// Created by osell on 2023/8/18. +// + +import UIKit + +// MARK: - DLToastConfig +public class DLToastConfig { + + fileprivate static var tag = NSStringFromClass(DLToastView.self).hash + + public enum Style { + case none + case loading + case progress + } + /// 背景图层颜色 + var bgColor: UIColor = .clear + /// 容器背景色 + var containerBgColor: UIColor = .black.withAlphaComponent(0.7) + /// 容器圆角 + var containerRadius: CGFloat = 12.0 + /// 文字颜色 + var textColor: UIColor = .white + /// 文字大小 + var textFont: UIFont = .systemFont(ofSize: 16, weight: .medium) + /// 图标大小 + var iconSize: CGSize = CGSize(width: 34, height: 34) + + public init() {} +} + +// MARK: - ToastImageView +class ToastImageView: UIImageView { + private var displayLink: CADisplayLink? + private var rotationAngle: CGFloat = 0.0 + + func startAnimation() { + displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:))) + displayLink?.add(to: .current, forMode: .common) + } + + @objc private func handleDisplayLink(_ displayLink: CADisplayLink) { + rotationAngle += CGFloat(displayLink.duration) * 2.0 * .pi + transform = CGAffineTransform(rotationAngle: rotationAngle) + } + + func stopAnimation() { + displayLink?.remove(from: .current, forMode: .common) + displayLink?.invalidate() + displayLink = nil + } + + deinit { + stopAnimation() + } +} + + +// MARK: - DLToastView +class DLToastView: UIView { + /// 完成后回调 + var completion: (() -> Void)? + + /// container + private lazy var containerView: UIView = { + let view = UIView() + view.backgroundColor = config.containerBgColor + view.setCornerRadius(config.containerRadius) + view.isUserInteractionEnabled = true + return view + }() + + /// 图标 + private lazy var iconImageView: ToastImageView = { + let view = ToastImageView() + return view + }() + + /// text + private lazy var textLabel: UILabel = { + let label = UILabel() + label.font = config.textFont + label.textColor = config.textColor + label.textAlignment = .center + label.numberOfLines = 0 + return label + }() + + private weak var viewForPresent: UIView? + private var config: DLToastConfig = DLToastConfig() + private var style: DLToastConfig.Style = .none + private var text: String? + private var iconImage: UIImage? + private var timer: DispatchSourceTimer? + + private override init(frame: CGRect) { + super.init(frame: .zero) + setupSubViews() + } + + init(iconImage: UIImage?, text: String?, config: DLToastConfig, style: DLToastConfig.Style) { + self.iconImage = iconImage + self.text = text + self.config = config + self.style = style + super.init(frame: .zero) + setupSubViews() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + /// 初始化视图布局 + private func setupSubViews() { + // 视图容器 + addSubview(containerView) + containerView.layoutChain + .center() + .left(48, relation: .greaterThanOrEqual) + .right(48, relation: .greaterThanOrEqual) + .top(kNaviHeight, relation: .greaterThanOrEqual) + .bottom(kNaviHeight, relation: .greaterThanOrEqual) + .width(100, relation: .greaterThanOrEqual) + + // 是否显示文字 + let isShowText = text?.isEmpty == false + var preView: UIView? + // 图片 + if let iconImage = iconImage { + iconImageView.image = iconImage + + containerView.addSubview(iconImageView) + iconImageView.layoutChain + .centerX() + .size(config.iconSize) + .top(isShowText ? 30 : 33) + .left(33, relation: isShowText ? .greaterThanOrEqual : .equal) + .right(33, relation: isShowText ? .greaterThanOrEqual : .equal) + + preView = iconImageView + } + + // 文字 + if isShowText { + textLabel.text = text + + containerView.addSubview(textLabel) + textLabel.layoutChain + .edgesHorzontal(16) + .width(112, relation: .greaterThanOrEqual) + + if let preView = preView { + textLabel.layoutChain + .topToBottomOfView(preView, offset: 20) + } else { + textLabel.layoutChain + .top(12) + } + + preView = textLabel + } + + if let preView = preView as? UIImageView { + preView.layoutChain + .bottom(33) + } else if let preView = preView as? UILabel { + preView.layoutChain + .bottom(isShowText && iconImage != nil ? 30 : 12) + } + } + + + deinit { + NotificationCenter.default.removeObserver(self) + if timer != nil { + timer?.cancel() + timer = nil + } + } +} + +extension DLToastView { + /// 显示Toast + /// - Parameter view: toast父视图 + func show(in view: UIView) { + viewForPresent = view + guard let viewForPresent = viewForPresent else { return } + backgroundColor = .clear + isUserInteractionEnabled = style == .loading + viewForPresent.addSubview(self) + self.layoutChain + .edges() + + alpha = 0 + sizeToFit() + containerView.center = .init(x: viewForPresent.frame.midX, y: viewForPresent.frame.midY) + containerView.transform = transform.scaledBy(x: 0.8, y: 0.8) + UIView.animate(withDuration: 0.25) { + self.alpha = 1 + self.containerView.transform = CGAffineTransform.identity + self.backgroundColor = self.config.bgColor + } + + // loading + if style == .loading { + NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) + // 执行动画 + iconImageView.startAnimation() + } + + // 根据文本内容自动消失 + if style == .none { + let text = text ?? "" + var time = Double(text.count) * 0.03 + 1.25 + time = time > 3.0 ? 3.0 : time + self.dismiss(delay: time, self.completion) + } + } + + /// 隐藏 + /// - Parameter completion: 完成回调 + func dismiss(delay: TimeInterval = 0, _ completion: (() -> Void)? = nil) { + // 有文字显示,自动消失 + if timer != nil { + timer?.cancel() + timer = nil + } + let queue = DispatchQueue(label: "com.toast.timer", qos: .background) + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now() + delay) + timer.setEventHandler { [weak self] in + guard let this = self else { return } + DispatchQueue.main.async { + UIView.animate(withDuration: 0.25) { + this.alpha = 0 + this.containerView.transform = this.containerView.transform.scaledBy(x: 0.2, y: 0.2) + } completion: { _ in + if this.style == .loading { + this.iconImageView.stopAnimation() + } + this.removeFromSuperview() + completion?() + } + } + } + timer.resume() + self.timer = timer + } + + @objc func applicationWillResignActive() { + if style == .loading { + iconImageView.stopAnimation() + } + } + + @objc func applicationDidBecomeActive() { + if style == .loading { + iconImageView.startAnimation() + } + } +} + +// MARK: - 通用Toast +public class DLToast { + + /// 显示loading + /// - Parameters: + /// - text: 文字 + /// - view: 在哪个视图上显示,默认在window + public static func showLoading(text: String? = nil, + in view: UIView? = nil) { + show(text: text, icon: UIImage(named: "loading"), style: .loading, in: view) + } + + /// 显示成功 + /// - Parameters: + /// - text: 文字 + /// - view: 在哪个视图上显示,默认在window + /// - completion: 完成后回调 + public static func showSuccess(text: String? = nil, + in view: UIView? = nil, + completion: (() -> Void)? = nil) { + show(text: text, icon: UIImage(named: "success"), in: view, completion: completion) + } + + /// 显示错误 + /// - Parameters: + /// - text: 文字 + /// - view: 在哪个视图上显示,默认在window + /// - completion: 完成后回调 + public static func showError(text: String? = nil, + in view: UIView? = nil, + completion: (() -> Void)? = nil) { + show(text: text, icon: UIImage(named: "fail"), in: view, completion: completion) + } + + /// 显示警告信息 + /// - Parameters: + /// - text: 文字 + /// - view: 在哪个视图上显示,默认在window + /// - completion: 完成后回调 + public static func showInfo(text: String? = nil, + in view: UIView? = nil, + completion: (() -> Void)? = nil) { + show(text: text, icon: UIImage(named: "warning"), in: view, completion: completion) + } + + /// 显示toast + /// - Parameters: + /// - text: 文字 + /// - icon: 图标 + /// - config: 配置信息 + /// - style: 样式 + /// - view: 在哪个视图上显示,默认在window + /// - completion: 完成后回调 + public static func show(text: String? = nil, + icon: UIImage? = nil, + config: DLToastConfig = DLToastConfig(), + style: DLToastConfig.Style = .none, + in view: UIView? = nil, + completion: (() -> Void)? = nil) { + DispatchQueue.main.async { + let superView = view ?? UIApplication.shared.windows.filter({ $0.isKeyWindow }).first + guard let superView = superView else { return } + if let toastView = superView.findSubView(with: DLToastConfig.tag) as? DLToastView { + toastView.removeFromSuperview() + } + let config = config + config.containerRadius = icon == nil ? 4 : config.containerRadius + let toastView = DLToastView(iconImage: icon, text: text, config: config, style: style) + toastView.tag = DLToastConfig.tag + toastView.completion = completion + toastView.show(in: superView) + } + } + + /// 隐藏toast + /// - Parameters: + /// - view: 从哪个视图隐藏 + /// - completion: 完成回调 + public static func dismiss(for view: UIView? = nil, + delay: TimeInterval = 0, + completion: (() -> Void)? = nil) { + DispatchQueue.main.async { + let superView = view ?? UIApplication.shared.windows.filter({ $0.isKeyWindow }).first + guard let toastView = superView?.findSubView(with: DLToastConfig.tag) as? DLToastView else { + completion?() + return + } + toastView.dismiss(delay: delay, completion) + } + } +} + +// MARK: - UIView + Toast +extension DLWrapper where Base: UIView { + + /// 显示loading + /// - Parameters: + /// - text: 文字 + public func showLoading(text: String? = nil) { + DLToast.showLoading(text: text, in: base) + } + + /// 显示成功 + /// - Parameters: + /// - text: 文字 + /// - view: 在哪个视图上显示,默认在window + /// - completion: 完成后回调 + public func showSuccess(text: String? = nil, + completion: (() -> Void)? = nil) { + DLToast.showSuccess(text: text, in: base, completion: completion) + } + + /// 显示错误 + /// - Parameters: + /// - text: 文字 + /// - completion: 完成后回调 + public func showError(text: String? = nil, + completion: (() -> Void)? = nil) { + DLToast.showError(text: text, in: base, completion: completion) + } + + /// 显示警告信息 + /// - Parameters: + /// - text: 文字 + /// - completion: 完成后回调 + public func showInfo(text: String? = nil, + completion: (() -> Void)? = nil) { + DLToast.showInfo(text: text, in: base, completion: completion) + } + + /// 显示toast + /// - Parameters: + /// - text: 文字 + /// - icon: 图标 + /// - config: 配置信息 + /// - style: 样式 + /// - completion: 完成后回调 + public func show(text: String, + icon: UIImage? = nil, + config: DLToastConfig = DLToastConfig(), + style: DLToastConfig.Style = .none, + completion: (() -> Void)? = nil) { + DLToast.show(text: text, icon: icon, config: config, style: style, in: base, completion: completion) + } + + /// 隐藏toast + /// - Parameters: + /// - completion: 完成回调 + public func dismiss(delay: TimeInterval = 0, + completion: (() -> Void)? = nil) { + DLToast.dismiss(for: base, delay: delay, completion: completion) + } +} + +// MARK: - UIViewController + Toast +extension DLWrapper where Base: UIViewController { + /// 显示loading + /// - Parameters: + /// - text: 文字 + public func showLoading(text: String? = nil) { + DLToast.showLoading(text: text, in: base.view) + } + + /// 显示成功 + /// - Parameters: + /// - text: 文字 + /// - view: 在哪个视图上显示,默认在window + /// - completion: 完成后回调 + public func showSuccess(text: String? = nil, + completion: (() -> Void)? = nil) { + DLToast.showSuccess(text: text, in: base.view, completion: completion) + } + + /// 显示错误 + /// - Parameters: + /// - text: 文字 + /// - completion: 完成后回调 + public func showError(text: String? = nil, + completion: (() -> Void)? = nil) { + DLToast.showError(text: text, in: base.view, completion: completion) + } + + /// 显示警告信息 + /// - Parameters: + /// - text: 文字 + /// - completion: 完成后回调 + public func showInfo(text: String? = nil, + completion: (() -> Void)? = nil) { + DLToast.showInfo(text: text, in: base.view, completion: completion) + } + + /// 显示toast + /// - Parameters: + /// - text: 文字 + /// - icon: 图标 + /// - config: 配置信息 + /// - style: 样式 + /// - completion: 完成后回调 + public func show(text: String, + icon: UIImage? = nil, + config: DLToastConfig = DLToastConfig(), + style: DLToastConfig.Style = .none, + completion: (() -> Void)? = nil) { + DLToast.show(text: text, icon: icon, config: config, style: style, in: base.view, completion: completion) + } + + /// 隐藏toast + /// - Parameters: + /// - completion: 完成回调 + public func dismiss(delay: TimeInterval = 0, + completion: (() -> Void)? = nil) { + DLToast.dismiss(for: base.view, delay: delay, completion: completion) + } +} diff --git a/QuickLocation/UIKit/CollectionHFlowLayout.swift b/QuickLocation/UIKit/CollectionHFlowLayout.swift new file mode 100644 index 00000000..b8341c8a --- /dev/null +++ b/QuickLocation/UIKit/CollectionHFlowLayout.swift @@ -0,0 +1,70 @@ +// +// CollectionHFlowLayout.swift +// dinoGo +// +// Created by osell on 2023/1/17. +// Copyright © 2023 dino. All rights reserved. +// + +import UIKit + +class CollectionHFlowLayout: UICollectionViewLayout { + + var rows: Int = 5 + var colums: Int = 2 + var itemSize: CGSize = .zero + var hSpacing: CGFloat = 10 + var vSpacing: CGFloat = 10 + var sectionInset: UIEdgeInsets = .zero + + var attributesArr: [UICollectionViewLayoutAttributes] = [] + + var contentWidth: CGFloat = 0 + var page = 0 + // MARK: - Lifecycle + override func prepare() { + super.prepare() + attributesArr = [] + contentWidth = 0 + page = 0 + let pageTotal = rows * colums + guard let itemCount = collectionView?.numberOfItems(inSection: 0) else { return } + + for index in 0.. UICollectionViewLayoutAttributes? { + attributesArr[indexPath.item] + } + + override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { + attributesArr.compactMap { + if rect.contains($0.frame) { + return $0 + } + return nil + } + } + + + override var collectionViewContentSize: CGSize { + var height = itemSize.height * CGFloat(rows) + height = height + CGFloat(rows - 1) * vSpacing + sectionInset.top + sectionInset.bottom + return CGSize(width: CGFloat(page + 1) * kScreenWidth, height: height) + } +} diff --git a/QuickLocation/UIKit/EmptyDataSet/DLEmptyDataSet.swift b/QuickLocation/UIKit/EmptyDataSet/DLEmptyDataSet.swift new file mode 100644 index 00000000..0db5a116 --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/DLEmptyDataSet.swift @@ -0,0 +1,213 @@ +// +// EmptyDataSet.swift +// JiuLaiBao +// +// Created by 霹雳火 on 01/06/2018. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import Foundation +import RxSwift +import UIKit + +private var emptyDataSetAssociatedKey: UInt8 = 0 + +public extension DLWrapper where Base: UIScrollView { + /// DLEmptyDataSet + var emptyDataSet: DLEmptyDataSet? { objc_getAssociatedObject(base, &emptyDataSetAssociatedKey) as? DLEmptyDataSet } + + /// + /// - Parameters: + /// - customEmptyHandler: 自定义Empty样式回调,可以对empty进行设置 + /// - customButtonDidTap: 自定义按钮点击回调 + /// - didTapRefresh: 网络失败按钮点击事件回调 + /// - Returns: DLEmptyDataSet + @discardableResult + func addEmptyDataSet(customEmptyHandler: ((DLEmptyDataSet) -> Void)? = nil, + customButtonDidTap: (() -> Void)? = nil, + didTapRefresh: (() -> Void)? = nil) -> DLEmptyDataSet { + let emptyDataSet = DLEmptyDataSet(scrollView: base) + emptyDataSet.didTapRefresh = didTapRefresh + emptyDataSet.customDidTap = customButtonDidTap + customEmptyHandler?(emptyDataSet) + objc_setAssociatedObject(base, &emptyDataSetAssociatedKey, emptyDataSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return emptyDataSet + } +} + +public struct EmptyDataSetConfig { + static public var titleColor = UIColor(hexStr: "#666666") + static public var detailColor = UIColor(hexStr: "#999999") + static public var emptyNoDataTitle = "oapp_EmptyNoData" + static public var emptyNoDataDetail = "" + static public var emptyNoDataImage = UIImage(named: "empty_data") + static public var emptyNetworkErrorTitle = "请检查网络连接" + static public var emptyNetworkErrorDetail = "" + static public var emptyNetworkErrorImage = UIImage(named: "empty_network") + static public var emptyReloadButtonImage = UIImage(named: "empty_reload") + static public var reloadButtonTitle = "重新加载" + static public var customButtonTitle = "" + static public var backgroundColor: UIColor = .clear + static public var spaceHeight: CGFloat = 15.0 + + /// 重置 + public static func resetConfig() { + titleColor = UIColor(hexStr: "#666666") + detailColor = UIColor(hexStr: "#999999") + emptyNoDataTitle = "暂无数据" + emptyNoDataDetail = "" + emptyNoDataImage = UIImage(named: "empty_data") + emptyNetworkErrorTitle = "请检查网络连接" + emptyNetworkErrorDetail = "" + emptyNetworkErrorImage = UIImage(named: "empty_network") + emptyReloadButtonImage = UIImage(named: "empty_reload") + customButtonTitle = "" + backgroundColor = .clear + } +} + +public class DLEmptyDataSet: NSObject { + + private var disposeBag = DisposeBag() + private weak var scrollView: UIScrollView! + private var refreshStatus: RefreshStatus? + private var isEmptyVariable = BehaviorSubject(value: nil) + // 是否开始就显示empty占位图 + private var shouldBeForcedToDisplay = false + public var titleColor = EmptyDataSetConfig.titleColor + public var detailColor = EmptyDataSetConfig.detailColor + public var emptyNoDataTitle = EmptyDataSetConfig.emptyNoDataTitle + public var emptyNoDataDetail = EmptyDataSetConfig.emptyNoDataDetail + public var emptyNoDataImage = EmptyDataSetConfig.emptyNoDataImage + public var emptyNetworkErrorTitle = EmptyDataSetConfig.emptyNetworkErrorTitle + public var emptyNetworkErrorDetail = EmptyDataSetConfig.emptyNetworkErrorDetail + public var emptyNetworkErrorImage = EmptyDataSetConfig.emptyNetworkErrorImage + public var emptyReloadButtonImage = EmptyDataSetConfig.emptyReloadButtonImage + public var reloadButtonTitle = EmptyDataSetConfig.reloadButtonTitle + public var customButtonTitle = EmptyDataSetConfig.customButtonTitle + public var backgroundColor: UIColor = EmptyDataSetConfig.backgroundColor + public var spaceHeight: CGFloat = EmptyDataSetConfig.spaceHeight + public var offsetY: CGFloat = 0 { + didSet { + scrollView.reloadEmptyDataSet() + } + } + + public var didTapRefresh: (() -> Void)? + public var customDidTap: (() -> Void)? + + required public init(scrollView: UIScrollView) { + super.init() + self.scrollView = scrollView + scrollView.emptyDataSetSource = self + scrollView.emptyDataSetDelegate = self + isEmptyVariable.asObservable().subscribe(onNext: { [unowned self] value in + if let _ = value { + self.scrollView.reloadEmptyDataSet() + } + }).disposed(by: disposeBag) + } + + public func update(status: RefreshStatus?, isEmpty: Bool, shouldForcedDisplay: Bool = false) { + refreshStatus = status + shouldBeForcedToDisplay = shouldForcedDisplay + isEmptyVariable.onNext(isEmpty) + } + + public func reset() { + shouldBeForcedToDisplay = false + refreshStatus = nil + isEmptyVariable.onNext(false) + } +} + +extension DLEmptyDataSet: EmptyDataSetSource, EmptyDataSetDelegate { + + // MARK: DZNEmptyDataSetSource + public func title(forEmptyDataSet _: UIScrollView) -> NSAttributedString? { + let text = refreshStatus == .invalidData ? emptyNetworkErrorTitle : emptyNoDataTitle + let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 13), + .foregroundColor: titleColor] + return NSAttributedString(string: text, attributes: attributes) + } + + public func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { + let text = refreshStatus == .invalidData ? emptyNetworkErrorDetail : emptyNoDataDetail + let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 13), + .foregroundColor: detailColor] + return NSAttributedString(string: text, attributes: attributes) + } + + public func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> String? { + return refreshStatus == .invalidData ? " \(reloadButtonTitle) " : customButtonTitle.isEmpty ? nil : " \(customButtonTitle) " + } + + public func buttonAttributedTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? { +// let errorAttri = NSAttributedString(string: "oapp_Reload".localizedString, +// font: UIFont.systemFont(ofSize: 15), +// color: UIColor.dl.rgb666666) +// return refreshStatus == .invalidData ? errorAttri : nil + return nil + } + + public func image(forEmptyDataSet _: UIScrollView) -> UIImage? { + return refreshStatus == .invalidData ? emptyNetworkErrorImage : emptyNoDataImage + } + +// public func buttonImage(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> UIImage! { +// return refreshStatus == .invalidData ? emptyReloadButtonImage : nil +// } + + public func backgroundColor(forEmptyDataSet _: UIScrollView) -> UIColor? { + return backgroundColor + } + + // MARK: DZNEmptyDataSetDelegate + public func emptyDataSetShouldDisplay(_: UIScrollView) -> Bool { + // 判断是否正在刷新 + guard refreshStatus != nil, + let isDisplay = try? isEmptyVariable.value() else { + return false + } + // 网络请求错误或者请求数据为空 + return isDisplay + } + + public func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView) -> Bool { + return true + } + + public func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool { + return true + } + + public func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) { + + } + + public func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) { + if customButtonTitle.isEmpty { + reset() + didTapRefresh?() + } + else { + customDidTap?() + } + } + + public func emptyDataSetWillAppear(_ scrollView: UIScrollView) { + scrollView.contentOffset = CGPoint() + } + + public func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { + return offsetY + } + + public func spaceHeight(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { + return spaceHeight + } + + @objc public func emptyDataSetShouldBeForcedToDisplay(_ scrollView: UIScrollView) -> Bool { + return shouldBeForcedToDisplay + } +} diff --git a/QuickLocation/UIKit/EmptyDataSet/EmptyDataSet.swift b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSet.swift new file mode 100644 index 00000000..f4d4372a --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSet.swift @@ -0,0 +1,433 @@ +// +// EmptyDataSet.swift +// EmptyDataSet-Swift +// +// Created by YZF on 28/6/17. +// Copyright © 2017年 Xiaoye. All rights reserved. +// + +import Foundation +import UIKit + +class WeakObjectContainer: NSObject { + weak var weakObject: AnyObject? + + init(with weakObject: Any?) { + super.init() + self.weakObject = weakObject as AnyObject? + } +} + +extension UIScrollView: UIGestureRecognizerDelegate { + + struct Key { + static var kEmptyDataSetSource = "emptyDataSetSource" + static var kEmptyDataSetDelegate = "emptyDataSetDelegate" + static var kEmptyDataSetView = "emptyDataSetView" + static var kConfigureEmptyDataSetView = "configureEmptyDataSetView" + } + + private var configureEmptyDataSetView: ((EmptyDataSetView) -> Void)? { + get { + return objc_getAssociatedObject(self, &Key.kConfigureEmptyDataSetView) as? (EmptyDataSetView) -> Void + } + set { + objc_setAssociatedObject(self, &Key.kConfigureEmptyDataSetView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + UIScrollView.swizzleReloadData + if self is UITableView { + UIScrollView.swizzleEndUpdates + } + } + } + + //MARK: - Public Property + public var emptyDataSetSource: EmptyDataSetSource? { + get { + let container = objc_getAssociatedObject(self, &Key.kEmptyDataSetSource) as? WeakObjectContainer + return container?.weakObject as? EmptyDataSetSource + } + set { + if newValue == nil { + self.invalidate() + } + + objc_setAssociatedObject(self, &Key.kEmptyDataSetSource, WeakObjectContainer(with: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + UIScrollView.swizzleReloadData + if self is UITableView { + UIScrollView.swizzleEndUpdates + } + } + } + + public var emptyDataSetDelegate: EmptyDataSetDelegate? { + get { + let container = objc_getAssociatedObject(self, &Key.kEmptyDataSetDelegate) as? WeakObjectContainer + return container?.weakObject as? EmptyDataSetDelegate + } + set { + if newValue == nil { + self.invalidate() + } + objc_setAssociatedObject(self, &Key.kEmptyDataSetDelegate, WeakObjectContainer(with: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + public var isEmptyDataSetVisible: Bool { + if let view = objc_getAssociatedObject(self, &Key.kEmptyDataSetView) as? EmptyDataSetView { + return !view.isHidden + } + return false + } + + //MARK: - privateProperty + public func emptyDataSetView(_ closure: @escaping (EmptyDataSetView) -> Void) { + configureEmptyDataSetView = closure + } + + private var emptyDataSetView: EmptyDataSetView? { + get { + if let view = objc_getAssociatedObject(self, &Key.kEmptyDataSetView) as? EmptyDataSetView { + return view + } else { + let view = EmptyDataSetView.init(frame: frame) + view.autoresizingMask = [.flexibleHeight, .flexibleWidth] + view.isHidden = true + let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTapContentView(_:))) + tapGesture.delegate = self + view.addGestureRecognizer(tapGesture) + view.button.addTarget(self, action: #selector(didTapDataButton(_:)), for: .touchUpInside) + + objc_setAssociatedObject(self, &Key.kEmptyDataSetView, view, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + + return view + } + } + set { + objc_setAssociatedObject(self, &Key.kEmptyDataSetView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + } + + internal var itemsCount: Int { + var items = 0 + + // UITableView support + if let tableView = self as? UITableView { + var sections = 1 + + if let dataSource = tableView.dataSource { + if dataSource.responds(to: #selector(UITableViewDataSource.numberOfSections(in:))) { + sections = dataSource.numberOfSections!(in: tableView) + } + if dataSource.responds(to: #selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:))) { + for i in 0 ..< sections { + items += dataSource.tableView(tableView, numberOfRowsInSection: i) + } + } + } + } else if let collectionView = self as? UICollectionView { + var sections = 1 + + if let dataSource = collectionView.dataSource { + if dataSource.responds(to: #selector(UICollectionViewDataSource.numberOfSections(in:))) { + sections = dataSource.numberOfSections!(in: collectionView) + } + if dataSource.responds(to: #selector(UICollectionViewDataSource.collectionView(_:numberOfItemsInSection:))) { + for i in 0 ..< sections { + items += dataSource.collectionView(collectionView, numberOfItemsInSection: i) + } + } + } + } + + return items + } + + //MARK: - Data Source Getters + private var titleLabelString: NSAttributedString? { + return emptyDataSetSource?.title(forEmptyDataSet: self) + } + + private var detailLabelString: NSAttributedString? { + return emptyDataSetSource?.description(forEmptyDataSet: self) + } + + private var image: UIImage? { + return emptyDataSetSource?.image(forEmptyDataSet: self) + } + + private var imageAnimation: CAAnimation? { + return emptyDataSetSource?.imageAnimation(forEmptyDataSet: self) + } + + private var imageTintColor: UIColor? { + return emptyDataSetSource?.imageTintColor(forEmptyDataSet: self) + } + + private func buttonTitle(for state: UIControl.State) -> String? { + return emptyDataSetSource?.buttonTitle(forEmptyDataSet: self, for: state) + } + + private func buttonAttributedTitle(for state: UIControl.State) -> NSAttributedString? { + return emptyDataSetSource?.buttonAttributedTitle(forEmptyDataSet: self, for: state) + } + + private func buttonImage(for state: UIControl.State) -> UIImage? { + return emptyDataSetSource?.buttonImage(forEmptyDataSet: self, for: state) + } + + private func buttonBackgroundImage(for state: UIControl.State) -> UIImage? { + return emptyDataSetSource?.buttonBackgroundImage(forEmptyDataSet: self, for: state) + } + + private var dataSetBackgroundColor: UIColor? { + return emptyDataSetSource?.backgroundColor(forEmptyDataSet: self) + } + + private var customView: UIView? { + return emptyDataSetSource?.customView(forEmptyDataSet: self) + } + + private var verticalOffset: CGFloat { + return emptyDataSetSource?.verticalOffset(forEmptyDataSet: self) ?? 0.0 + } + + private var verticalSpace: CGFloat { + return emptyDataSetSource?.spaceHeight(forEmptyDataSet: self) ?? 0.0 + } + + //MARK: - Delegate Getters & Events (Private) + + private var shouldFadeIn: Bool { + return emptyDataSetDelegate?.emptyDataSetShouldFadeIn(self) ?? true + } + + private var shouldDisplay: Bool { + return emptyDataSetDelegate?.emptyDataSetShouldDisplay(self) ?? true + } + + private var shouldBeForcedToDisplay: Bool { + return emptyDataSetDelegate?.emptyDataSetShouldBeForcedToDisplay(self) ?? false + } + + private var isTouchAllowed: Bool { + return emptyDataSetDelegate?.emptyDataSetShouldAllowTouch(self) ?? true + } + + private var isScrollAllowed: Bool { + return emptyDataSetDelegate?.emptyDataSetShouldAllowScroll(self) ?? false + } + + private var isImageViewAnimateAllowed: Bool { + return emptyDataSetDelegate?.emptyDataSetShouldAnimateImageView(self) ?? true + } + + private func willAppear() { + emptyDataSetDelegate?.emptyDataSetWillAppear(self) + emptyDataSetView?.willAppearHandle?() + } + + private func didAppear() { + emptyDataSetDelegate?.emptyDataSetDidAppear(self) + emptyDataSetView?.didAppearHandle?() + } + + private func willDisappear() { + emptyDataSetDelegate?.emptyDataSetWillDisappear(self) + emptyDataSetView?.willDisappearHandle?() + } + + private func didDisappear() { + emptyDataSetDelegate?.emptyDataSetDidDisappear(self) + emptyDataSetView?.didDisappearHandle?() + } + + @objc private func didTapContentView(_ sender: UITapGestureRecognizer) { + guard let view = sender.view else { return } + emptyDataSetDelegate?.emptyDataSet(self, didTapView: view) + emptyDataSetView?.didTapContentViewHandle?() + } + + @objc private func didTapDataButton(_ sender: UIButton) { + emptyDataSetDelegate?.emptyDataSet(self, didTapButton: sender) + emptyDataSetView?.didTapDataButtonHandle?() + } + + //MARK: - Reload APIs (Public) + public func reloadEmptyDataSet() { + guard (emptyDataSetSource != nil || configureEmptyDataSetView != nil) else { + return + } + + if (shouldDisplay && itemsCount == 0) || shouldBeForcedToDisplay { + // Notifies that the empty dataset view will appear + willAppear() + + if let view = emptyDataSetView { + + // Configure empty dataset fade in display + view.fadeInOnDisplay = shouldFadeIn + + if view.superview == nil { + // Send the view all the way to the back, in case a header and/or footer is present, as well as for sectionHeaders or any other content + if (self is UITableView) || (self is UICollectionView) || (subviews.count > 1) { + insertSubview(view, at: 0) + } else { + addSubview(view) + } + } + + // Removing view resetting the view and its constraints it very important to guarantee a good state + // If a non-nil custom view is available, let's configure it instead + view.prepareForReuse() + + if let customView = self.customView { + view.customView = customView + } else { + // Get the data from the data source + + let renderingMode: UIImage.RenderingMode = imageTintColor != nil ? .alwaysTemplate : .alwaysOriginal + + view.verticalSpace = verticalSpace + + // Configure Image + if let image = image { + view.imageView.image = image.withRenderingMode(renderingMode) +// emptyDataSetView.imageView.mj_size.width = image.size.width +// emptyDataSetView.imageView.mj_size.height = image.size.height + emptyDataSetView?.imageView.layoutChain.size(image.size) + if let imageTintColor = imageTintColor { + view.imageView.tintColor = imageTintColor + } + } + + // Configure title label + if let titleLabelString = titleLabelString { + view.titleLabel.attributedText = titleLabelString + } + + // Configure detail label + if let detailLabelString = detailLabelString { + view.detailLabel.attributedText = detailLabelString + } + + // Configure button + if let buttonImage = buttonImage(for: .normal) { + view.button.setImage(buttonImage, for: .normal) + view.button.setImage(self.buttonImage(for: .highlighted), for: .highlighted) + } + else if let buttonAttributedTitle = buttonAttributedTitle(for: .normal) { + view.button.setAttributedTitle(buttonAttributedTitle, for: .normal) + view.button.setAttributedTitle(self.buttonAttributedTitle(for: .highlighted), for: .highlighted) + view.button.setBackgroundImage(self.buttonBackgroundImage(for: .normal), for: .normal) + view.button.setBackgroundImage(self.buttonBackgroundImage(for: .highlighted), for: .highlighted) + } + else if let buttonTitle = buttonTitle(for: .normal) { + view.button.setTitle(buttonTitle, for: .normal) + view.button.setTitle(self.buttonTitle(for: .highlighted), for: .highlighted) + view.button.setBackgroundImage(self.buttonBackgroundImage(for: .normal), for: .normal) + view.button.setBackgroundImage(self.buttonBackgroundImage(for: .highlighted), for: .highlighted) + } + } + + // Configure offset + view.verticalOffset = verticalOffset + + // Configure the empty dataset view + view.backgroundColor = dataSetBackgroundColor + view.isHidden = false + view.clipsToBounds = true + + // Configure empty dataset userInteraction permission + view.isUserInteractionEnabled = isTouchAllowed + + // Configure scroll permission + self.isScrollEnabled = isScrollAllowed + + // Configure image view animation + if self.isImageViewAnimateAllowed { + if let animation = imageAnimation { + view.imageView.layer.add(animation, forKey: nil) + } + } else { + view.imageView.layer.removeAllAnimations() + } + + if let config = configureEmptyDataSetView { + config(view) + } + view.setupViews() +// view.setupConstraints() +// view.layoutIfNeeded() + } + + // Notifies that the empty dataset view did appear + didAppear() + } else if isEmptyDataSetVisible { + invalidate() + } + } + + private func invalidate() { + willDisappear() + if let view = emptyDataSetView { + view.prepareForReuse() + view.isHidden = true +// view.removeFromSuperview() +// emptyDataSetView = nil + } + self.isScrollEnabled = true + didDisappear() + } + + + //MARK: - Method Swizzling + @objc private func tableViewSwizzledReloadData() { + tableViewSwizzledReloadData() + reloadEmptyDataSet() + } + + @objc private func tableViewSwizzledEndUpdates() { + tableViewSwizzledEndUpdates() + reloadEmptyDataSet() + } + + @objc private func collectionViewSwizzledReloadData() { + collectionViewSwizzledReloadData() + reloadEmptyDataSet() + } + + private class func swizzleMethod(for aClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) { + let originalMethod = class_getInstanceMethod(aClass, originalSelector) + let swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector) + + let didAddMethod = class_addMethod(aClass, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) + + if didAddMethod { + class_replaceMethod(aClass, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) + } else { + method_exchangeImplementations(originalMethod!, swizzledMethod!) + } + } + + private static let swizzleReloadData: () = { +// let tableViewOriginalSelector = #selector(UITableView.reloadData) +// let tableViewSwizzledSelector = #selector(UIScrollView.tableViewSwizzledReloadData) +// +// swizzleMethod(for: UITableView.self, originalSelector: tableViewOriginalSelector, swizzledSelector: tableViewSwizzledSelector) +// +// let collectionViewOriginalSelector = #selector(UICollectionView.reloadData) +// let collectionViewSwizzledSelector = #selector(UIScrollView.collectionViewSwizzledReloadData) +// +// swizzleMethod(for: UICollectionView.self, originalSelector: collectionViewOriginalSelector, swizzledSelector: collectionViewSwizzledSelector) + }() + + private static let swizzleEndUpdates: () = { + let originalSelector = #selector(UITableView.endUpdates) + let swizzledSelector = #selector(UIScrollView.tableViewSwizzledEndUpdates) + + swizzleMethod(for: UITableView.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector) + }() +} + + + diff --git a/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetDelegate.swift b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetDelegate.swift new file mode 100644 index 00000000..2bd4b338 --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetDelegate.swift @@ -0,0 +1,143 @@ +// +// EmptyDataSetDelegate.swift +// EmptyDataSet-Swift +// +// Created by YZF on 27/6/17. +// Copyright © 2017年 Xiaoye. All rights reserved. +// + +import Foundation +import UIKit + + +/// The object that acts as the delegate of the empty datasets. +/// @discussion The delegate can adopt the DZNEmptyDataSetDelegate protocol. The delegate is not retained. All delegate methods are optional. +/// +/// @discussion All delegate methods are optional. Use this delegate for receiving action callbacks. +public protocol EmptyDataSetDelegate { + + /// Asks the delegate to know if the empty dataset should fade in when displayed. Default is true. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: true if the empty dataset should fade in. + func emptyDataSetShouldFadeIn(_ scrollView: UIScrollView) -> Bool + + /// Asks the delegate to know if the empty dataset should still be displayed when the amount of items is more than 0. Default is false. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: true if empty dataset should be forced to display + func emptyDataSetShouldBeForcedToDisplay(_ scrollView: UIScrollView) -> Bool + + /// Asks the delegate to know if the empty dataset should be rendered and displayed. Default is true. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: true if the empty dataset should show. + func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool + + /// Asks the delegate for touch permission. Default is true. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: true if the empty dataset receives touch gestures. + func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView) -> Bool + + /// Asks the delegate for scroll permission. Default is false. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: true if the empty dataset is allowed to be scrollable. + func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool + + /// Asks the delegate for image view animation permission. Default is false. + /// Make sure to return a valid CAAnimation object from imageAnimationForEmptyDataSet: + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: true if the empty dataset is allowed to animate + func emptyDataSetShouldAnimateImageView(_ scrollView: UIScrollView) -> Bool + + /// Tells the delegate that the empty dataset view was tapped. + /// Use this method either to resignFirstResponder of a textfield or searchBar. + /// + /// - Parameters: + /// - scrollView: scrollView A scrollView subclass informing the delegate. + /// - view: the view tapped by the user + func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) + + /// Tells the delegate that the action button was tapped. + /// + /// - Parameters: + /// - scrollView: A scrollView subclass informing the delegate. + /// - button: the button tapped by the user + func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) + + /// Tells the delegate that the empty data set will appear. + /// + /// - Parameter scrollView: A scrollView subclass informing the delegate. + func emptyDataSetWillAppear(_ scrollView: UIScrollView) + + /// Tells the delegate that the empty data set did appear. + /// + /// - Parameter scrollView: A scrollView subclass informing the delegate. + func emptyDataSetDidAppear(_ scrollView: UIScrollView) + + /// Tells the delegate that the empty data set will disappear. + /// + /// - Parameter scrollView: A scrollView subclass informing the delegate. + func emptyDataSetWillDisappear(_ scrollView: UIScrollView) + + /// Tells the delegate that the empty data set did disappear. + /// + /// - Parameter scrollView: A scrollView subclass informing the delegate. + func emptyDataSetDidDisappear(_ scrollView: UIScrollView) + +} + +public extension EmptyDataSetDelegate { + + func emptyDataSetShouldFadeIn(_ scrollView: UIScrollView) -> Bool { + return true + } + + func emptyDataSetShouldBeForcedToDisplay(_ scrollView: UIScrollView) -> Bool { + return false + } + + func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool { + return true + } + + func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView) -> Bool { + return true + } + + func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool { + return false + } + + func emptyDataSetShouldAnimateImageView(_ scrollView: UIScrollView) -> Bool { + return true + } + + func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) { + + } + + func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) { + + } + + func emptyDataSetWillAppear(_ scrollView: UIScrollView) { + + } + + func emptyDataSetDidAppear(_ scrollView: UIScrollView) { + + } + + func emptyDataSetWillDisappear(_ scrollView: UIScrollView) { + + } + + func emptyDataSetDidDisappear(_ scrollView: UIScrollView) { + + } + +} diff --git a/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetSource.swift b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetSource.swift new file mode 100644 index 00000000..852ea56e --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetSource.swift @@ -0,0 +1,162 @@ +// +// Protocols.swift +// EmptyDataSet-Swift +// +// Created by YZF on 27/6/17. +// Copyright © 2017年 Xiaoye. All rights reserved. +// + +import Foundation +import UIKit + + +/// The object that acts as the data source of the empty datasets. +/// @discussion The data source must adopt the DZNEmptyDataSetSource protocol. The data source is not retained. All data source methods are optional. +public protocol EmptyDataSetSource { + + /// Asks the data source for the title of the dataset. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + /// + /// - Parameter scrollView: scrollView A scrollView subclass informing the data source. + /// - Returns: An attributed string for the dataset title, combining font, text color, text pararaph style, etc. + func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? + + /// Asks the data source for the description of the dataset. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + /// + /// - Parameter scrollView: scrollView A scrollView subclass informing the data source. + /// - Returns: An attributed string for the dataset description text, combining font, text color, text pararaph style, etc. + func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? + + /// Asks the data source for the image of the dataset. + /// + /// - Parameter scrollView: A scrollView subclass informing the data source. + /// - Returns: An image for the dataset. + func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? + + /// Asks the data source for a tint color of the image dataset. Default is nil. + /// + /// - Parameter scrollView: A scrollView subclass object informing the data source. + /// - Returns: A color to tint the image of the dataset. + func imageTintColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? + + /// Asks the data source for the image animation of the dataset. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: image animation + func imageAnimation(forEmptyDataSet scrollView: UIScrollView) -> CAAnimation? + + /// Asks the data source for the title to be used for the specified button state. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + /// + /// - Parameters: + /// - scrollView: A scrollView subclass object informing the data source. + /// - forState: The state that uses the specified title. The possible values are described in UIControlState. + /// - Returns: An attributed string for the dataset button title, combining font, text color, text pararaph style, etc. + func buttonAttributedTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? + + /// Asks the data source for the title to be used for the specified button state. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + /// + /// - Parameters: + /// - scrollView: A scrollView subclass object informing the data source. + /// - forState: The state that uses the specified title. The possible values are described in UIControlState. + /// - Returns: An string for the dataset button title + func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> String? + + /// Asks the data source for the image to be used for the specified button state. + /// This method will override buttonTitleForEmptyDataSet:forState: and present the image only without any text. + /// + /// - Parameters: + /// - scrollView: A scrollView subclass object informing the data source. + /// - forState: The state that uses the specified title. The possible values are described in UIControlState. + /// - Returns: An image for the dataset button imageview. + func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? + + /// Asks the data source for a background image to be used for the specified button state. + /// There is no default style for this call. + /// + /// - Parameters: + /// - scrollView: A scrollView subclass informing the data source. + /// - forState: The state that uses the specified image. The values are described in UIControlState. + /// - Returns: An attributed string for the dataset button title, combining font, text color, text pararaph style, etc. + func buttonBackgroundImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? + + /// Asks the data source for the background color of the dataset. Default is clear color. + /// + /// - Parameter scrollView: A scrollView subclass object informing the data source. + /// - Returns: A color to be applied to the dataset background view. + func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? + + /// Asks the data source for a custom view to be displayed instead of the default views such as labels, imageview and button. Default is nil. + /// Use this method to show an activity view indicator for loading feedback, or for complete custom empty data set. + /// Returning a custom view will ignore -offsetForEmptyDataSet and -spaceHeightForEmptyDataSet configurations. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: The custom view. + func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? + + /// Asks the data source for a offset for vertical alignment of the content. Default is 0. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: The offset for vertical alignment. + func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat + + /// Asks the data source for a vertical space between elements. Default is 11 pts. + /// + /// - Parameter scrollView: A scrollView subclass object informing the delegate. + /// - Returns: The space height between elements. + func spaceHeight(forEmptyDataSet scrollView: UIScrollView) -> CGFloat + +} + +public extension EmptyDataSetSource { + + func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { + return nil + } + + func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { + return nil + } + + func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? { + return nil + } + + func imageTintColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? { + return nil + } + + func imageAnimation(forEmptyDataSet scrollView: UIScrollView) -> CAAnimation? { + return nil + } + + func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? { + return nil + } + + func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? { + return nil + } + + func buttonBackgroundImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? { + return nil + } + + func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? { + return nil + } + + func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? { + return nil + } + + func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { + return 0 + } + + func spaceHeight(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { + return 11 + } +} diff --git a/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetView+Extension.swift b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetView+Extension.swift new file mode 100644 index 00000000..2a079169 --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetView+Extension.swift @@ -0,0 +1,202 @@ +// +// EmptyDataSetView+Extension.swift +// EmptyDataSet-Swift +// +// Created by YZF on 3/7/17. +// Copyright © 2017年 Xiaoye. All rights reserved. +// + +import Foundation +import UIKit + +extension EmptyDataSetView { + + //MARK: - Data Source + + /// Asks the data source for the title of the dataset. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + @discardableResult + public func titleLabelString(_ attributedString: NSAttributedString?) -> Self { + titleLabel.attributedText = attributedString + return self + } + + /// Asks the data source for the description of the dataset. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + @discardableResult + public func detailLabelString(_ attributedString: NSAttributedString?) -> Self { + detailLabel.attributedText = attributedString + return self + } + + /// Asks the data source for the image of the dataset. + @discardableResult + public func image(_ image: UIImage?) -> Self { + imageView.image = image + return self + } + + /// Asks the data source for a tint color of the image dataset. Default is nil. + @discardableResult + public func imageTintColor(_ imageTintColor: UIColor?) -> Self { + imageView.tintColor = imageTintColor + return self + } + + /// Asks the data source for the image animation of the dataset. + @discardableResult + public func imageAnimation(_ imageAnimation: CAAnimation?) -> Self { + if let ani = imageAnimation { + imageView.layer.add(ani, forKey: nil) + } + return self + } + + /// Asks the data source for the title to be used for the specified button state. + /// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string. + @discardableResult + public func buttonTitle(_ buttonTitle: NSAttributedString?, for state: UIControl.State) -> Self { + button.setAttributedTitle(buttonTitle, for: state) + return self + } + + /// Asks the data source for the image to be used for the specified button state. + /// This method will override buttonTitleForEmptyDataSet:forState: and present the image only without any text. + @discardableResult + public func buttonImage(_ buttonImage: UIImage?, for state: UIControl.State) -> Self { + button.setImage(buttonImage, for: state) + return self + } + + /// Asks the data source for a background image to be used for the specified button state. + /// There is no default style for this call. + @discardableResult + public func buttonBackgroundImage(_ buttonBackgroundImage: UIImage?, for state: UIControl.State) -> Self { + button.setBackgroundImage(buttonBackgroundImage, for: state) + return self + } + + /// Asks the data source for the background color of the dataset. Default is clear color. + @discardableResult + public func dataSetBackgroundColor(_ backgroundColor: UIColor?) -> Self { + self.backgroundColor = backgroundColor + return self + } + + /// Asks the data source for a custom view to be displayed instead of the default views such as labels, imageview and button. Default is nil. + /// Use this method to show an activity view indicator for loading feedback, or for complete custom empty data set. + /// Returning a custom view will ignore -offsetForEmptyDataSet and -spaceHeightForEmptyDataSet configurations. + @discardableResult + public func customView(_ customView: UIView?) -> Self { + self.customView = customView + return self + } + + /// Asks the data source for a offset for vertical alignment of the content. Default is 0. + @discardableResult + public func verticalOffset(_ offset: CGFloat) -> Self { + verticalOffset = offset + return self + } + + /// Asks the data source for a vertical space between elements. Default is 11 pts. + @discardableResult + public func verticalSpace(_ space: CGFloat) -> Self { + verticalSpace = space + return self + } + + //MARK: - Delegate & Events + /// Asks the delegate to know if the empty dataset should fade in when displayed. Default is true. + @discardableResult + public func shouldFadeIn(_ bool: Bool) -> Self { + fadeInOnDisplay = bool + return self + } + + /// Asks the delegate to know if the empty dataset should still be displayed when the amount of items is more than 0. Default is false. + @discardableResult + public func shouldBeForcedToDisplay(_ bool: Bool) -> Self { + isHidden = !bool + return self + } + + /// Asks the delegate to know if the empty dataset should be rendered and displayed. Default is true. + @discardableResult + public func shouldDisplay(_ bool: Bool) -> Self { + if let superview = self.superview as? UIScrollView { + isHidden = !(bool && superview.itemsCount == 0) + } + return self + } + + /// Asks the delegate for touch permission. Default is true. + @discardableResult + public func isTouchAllowed(_ bool: Bool) -> Self { + isUserInteractionEnabled = bool + return self + } + + /// Asks the delegate for scroll permission. Default is false. + @discardableResult + public func isScrollAllowed(_ bool: Bool) -> Self { + if let superview = superview as? UIScrollView { + superview.isScrollEnabled = bool + } + return self + } + + /// Asks the delegate for image view animation permission. Default is false. + /// Make sure to return a valid CAAnimation object from imageAnimationForEmptyDataSet: + @discardableResult + public func isImageViewAnimateAllowed(_ bool: Bool) -> Self { + if !bool { + imageView.layer.removeAllAnimations() + } + return self + } + + /// Tells the delegate that the empty dataset view was tapped. + /// Use this method either to resignFirstResponder of a textfield or searchBar. + @discardableResult + public func didTapContentView(_ closure: @escaping () -> (Void)) -> Self { + didTapContentViewHandle = closure + return self + } + + /// Tells the delegate that the action button was tapped. + @discardableResult + public func didTapDataButton(_ closure: @escaping () -> (Void)) -> Self { + didTapDataButtonHandle = closure + return self + } + + /// Tells the delegate that the empty data set will appear. + @discardableResult + public func willAppear(_ closure: @escaping () -> (Void)) -> Self { + willAppearHandle = closure + return self + } + + /// Tells the delegate that the empty data set did appear. + @discardableResult + public func didAppear(_ closure: @escaping () -> (Void)) -> Self { + didAppearHandle = closure + return self + } + + /// Tells the delegate that the empty data set will disappear. + @discardableResult + public func willDisappear(_ closure: @escaping () -> (Void)) -> Self { + willDisappearHandle = closure + return self + } + + /// Tells the delegate that the empty data set did disappear. + @discardableResult + public func didDisappear(_ closure: @escaping () -> (Void)) -> Self { + didDisappearHandle = closure + return self + } + +} diff --git a/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetView.swift b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetView.swift new file mode 100644 index 00000000..5cc1e641 --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/EmptyDataSetView.swift @@ -0,0 +1,323 @@ +// +// EmptyDataSetView.swift +// EmptyDataSet-Swift +// +// Created by YZF on 28/6/17. +// Copyright © 2017年 Xiaoye. All rights reserved. +// + +import Foundation +import UIKit + +public class EmptyDataSetView: UIView { + + lazy var stackView: UIStackView = { + let view = UIStackView(arrangedSubviews: [imageView, titleLabel, detailLabel, button]) + view.axis = .vertical + view.spacing = 10 + view.alignment = .center + view.distribution = .fill + view.setCustomSpacing(15, after: imageView) + view.setCustomSpacing(20, after: detailLabel) + return view + }() + + internal lazy var contentView: UIView = { + let contentView = UIView() + contentView.translatesAutoresizingMaskIntoConstraints = false + contentView.backgroundColor = UIColor.clear + contentView.isUserInteractionEnabled = true + contentView.alpha = 0 + return contentView + }() + + internal lazy var imageView: UIImageView = { + let imageView = UIImageView() + imageView.translatesAutoresizingMaskIntoConstraints = false + imageView.backgroundColor = UIColor.clear + imageView.contentMode = .scaleAspectFit + imageView.isUserInteractionEnabled = false + imageView.accessibilityIdentifier = "empty set background image" + self.contentView.addSubview(imageView) + return imageView + }() + + internal lazy var titleLabel: UILabel = { + let titleLabel = UILabel() + titleLabel.translatesAutoresizingMaskIntoConstraints = false + titleLabel.backgroundColor = UIColor.clear + + titleLabel.font = UIFont.systemFont(ofSize: 27.0) + titleLabel.textColor = UIColor(white: 0.6, alpha: 1.0) + titleLabel.textAlignment = .center + titleLabel.lineBreakMode = .byWordWrapping + titleLabel.numberOfLines = 0 + titleLabel.accessibilityIdentifier = "empty set title" + self.contentView.addSubview(titleLabel) + return titleLabel + }() + + internal lazy var detailLabel: UILabel = { + let detailLabel = UILabel() + detailLabel.translatesAutoresizingMaskIntoConstraints = false + detailLabel.backgroundColor = UIColor.clear + + detailLabel.font = UIFont.systemFont(ofSize: 17.0) + detailLabel.textColor = UIColor(white: 0.6, alpha: 1.0) + detailLabel.textAlignment = .center + detailLabel.lineBreakMode = .byWordWrapping + detailLabel.numberOfLines = 0 + detailLabel.accessibilityIdentifier = "empty set detail label" + self.contentView.addSubview(detailLabel) + return detailLabel + }() + + internal lazy var button: UIButton = { + let button = UIButton() + button.titleLabel?.font = .systemFont(ofSize: 12) + button.layer.cornerRadius = 5.0 + button.translatesAutoresizingMaskIntoConstraints = false + button.backgroundColor = UIColor.clear + button.contentHorizontalAlignment = .center + button.contentVerticalAlignment = .center + button.accessibilityIdentifier = "empty set button" + button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 13, bottom: 10, right: 13) + + self.contentView.addSubview(button) + return button + }() + + private var canShowImage: Bool { + return imageView.image != nil + } + + private var canShowTitle: Bool { + if let attributedText = titleLabel.attributedText { + return attributedText.length > 0 + } + return false + } + + private var canShowDetail: Bool { + if let attributedText = detailLabel.attributedText { + return attributedText.length > 0 + } + return false + } + + private var canShowButton: Bool { + if let attributedTitle = button.attributedTitle(for: .normal) { + return attributedTitle.length > 0 + } else if let _ = button.image(for: .normal) { + return true + } else if let buttonText = button.title(for: .normal) { + return buttonText.length > 0 + } + + return false + } + + + internal var customView: UIView? { + willSet { + if let customView = customView { + customView.removeFromSuperview() + } + } + didSet { + if let customView = customView { + customView.translatesAutoresizingMaskIntoConstraints = false + self.addSubview(customView) + } + } + } + + internal var fadeInOnDisplay = false + internal var verticalOffset: CGFloat = 0 + internal var verticalSpace: CGFloat = 11 + + internal var didTapContentViewHandle: (() -> Void)? + internal var didTapDataButtonHandle: (() -> Void)? + internal var willAppearHandle: (() -> Void)? + internal var didAppearHandle: (() -> Void)? + internal var willDisappearHandle: (() -> Void)? + internal var didDisappearHandle: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + addSubview(contentView) + } + + required public init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override public func didMoveToSuperview() { + if let superviewBounds = superview?.bounds { + frame = CGRect(x: 0, y: 0, width: superviewBounds.width, height: superviewBounds.height) + } + if fadeInOnDisplay { + UIView.animate(withDuration: 0.25) { + self.contentView.alpha = 1 + } + } else { + contentView.alpha = 1 + } + } + + // MARK: - Action Methods + + internal func removeAllConstraints() { + removeConstraints(constraints) + contentView.removeConstraints(contentView.constraints) + } + + internal func prepareForReuse() { + titleLabel.text = nil + detailLabel.text = nil + imageView.image = nil + button.setImage(nil, for: .normal) + button.setImage(nil, for: .highlighted) + button.setAttributedTitle(nil, for: .normal) + button.setAttributedTitle(nil, for: .highlighted) + button.setBackgroundImage(nil, for: .normal) + button.setBackgroundImage(nil, for: .highlighted) + customView = nil + + removeAllConstraints() + } + + internal func setupViews() { + addSubview(stackView) + stackView.layoutChain + .centerX() + .centerY(self, offset: verticalOffset) + + imageView.isHidden = !canShowImage + titleLabel.isHidden = !canShowTitle + detailLabel.isHidden = !canShowDetail + button.isHidden = !canShowButton + } + + // MARK: - Auto-Layout Configuration + internal func setupConstraints() { + + // First, configure the content view constaints + // The content view must alway be centered to its superview + let centerXConstraint = NSLayoutConstraint(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0) + let centerYConstraint = NSLayoutConstraint(item: contentView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0) + + self.addConstraints([centerXConstraint, centerYConstraint]) + self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[contentView]|", options: [], metrics: nil, views: ["contentView": contentView])) + + // When a custom offset is available, we adjust the vertical constraints' constants + if (verticalOffset != 0 && constraints.count > 0) { + centerYConstraint.constant = verticalOffset + } + + if let customView = customView { + let centerXConstraint = NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0) + let centerYConstraint = NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0) + + let customViewHeight = customView.frame.height + let customViewWidth = customView.frame.width + var heightConstarint: NSLayoutConstraint! + var widthConstarint: NSLayoutConstraint! + + if(customViewHeight == 0) { + heightConstarint = NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .lessThanOrEqual, toItem: self, attribute: .height, multiplier: 1, constant: 0.0) + } else { + heightConstarint = NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: customViewHeight) + } + if(customViewWidth == 0) { + widthConstarint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .lessThanOrEqual, toItem: self, attribute: .width, multiplier: 1, constant: 0.0) + } else { + widthConstarint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: customViewWidth) + } + + // When a custom offset is available, we adjust the vertical constraints' constants + if (verticalOffset != 0) { + centerYConstraint.constant = verticalOffset + } + self.addConstraints([centerXConstraint, centerYConstraint]) + self.addConstraints([heightConstarint, widthConstarint]) +// contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[customView]|", options: [], metrics: nil, views: ["customView": customView])) +// contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[customView]|", options: [], metrics: nil, views: ["customView": customView])) + } else { + + let width = frame.width > 0 ? frame.width : UIScreen.main.bounds.width + let padding = roundf(Float(width/16.0)) + let verticalSpace = self.verticalSpace // Default is 11 pts + + var subviewStrings: [String] = [] + var views: [String: UIView] = [:] + let metrics = ["padding": padding] + + // Assign the image view's horizontal constraints + if canShowImage { + imageView.isHidden = false + + subviewStrings.append("imageView") + views[subviewStrings.last!] = imageView + + contentView.addConstraint(NSLayoutConstraint.init(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) + } else { + imageView.isHidden = true + } + + // Assign the title label's horizontal constraints + if (canShowTitle) { + titleLabel.isHidden = false + subviewStrings.append("titleLabel") + views[subviewStrings.last!] = titleLabel + + contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(padding)-[titleLabel(>=0)]-(padding)-|", options: [], metrics: metrics, views: views)) + } else { + titleLabel.isHidden = true + } + + // Assign the detail label's horizontal constraints + if (canShowDetail) { + detailLabel.isHidden = false + subviewStrings.append("detailLabel") + views[subviewStrings.last!] = detailLabel + + contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(padding)-[detailLabel(>=0)]-(padding)-|", options: [], metrics: metrics, views: views)) + } else { + detailLabel.isHidden = true + } + + // Assign the button's horizontal constraints + if (canShowButton) { + button.isHidden = false + subviewStrings.append("button") + views[subviewStrings.last!] = button + contentView.addConstraint(NSLayoutConstraint.init(item: button, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) +// contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[button]", options: [], metrics: metrics, views: views)) + } else { + button.isHidden = true + } + + var verticalFormat = String() + + // Build a dynamic string format for the vertical constraints, adding a margin between each element. Default is 11 pts. + for i in 0 ..< subviewStrings.count { + let string = subviewStrings[i] + verticalFormat += "[\(string)]" + + if i < subviewStrings.count - 1 { + verticalFormat += "-(\(verticalSpace))-" + } + } + + // Assign the vertical constraints to the content view + if !verticalFormat.isEmpty { + contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|\(verticalFormat)|", options: [], metrics: metrics, views: views)) + } + + } + + } + +} + diff --git a/QuickLocation/UIKit/EmptyDataSet/RefreshStyle.swift b/QuickLocation/UIKit/EmptyDataSet/RefreshStyle.swift new file mode 100644 index 00000000..dccec5a0 --- /dev/null +++ b/QuickLocation/UIKit/EmptyDataSet/RefreshStyle.swift @@ -0,0 +1,62 @@ +// +// RefreshStyle.swift +// GXM-CRM +// +// Created by 霹雳火 on 10/11/2017. +// Copyright © 2017 GuoXiaoMei. All rights reserved. +// + +import Foundation +import MJRefresh +import RxSwift +import RxCocoa + +public enum RefreshStatus: Int { + case invalidData // 无效的数据 + case hasMoreData // 还有更多数据 + case noMoreData // 没有更多数据 +} + +public enum RequestStatus { + case begin + case end +} + +/** + 设置刷新状态 + */ +public extension UIScrollView { + + func refresh(status: RefreshStatus, isEmpty: Bool, shouldForcedDisplay: Bool = false) { + // 刷新空数据占位 + dl.emptyDataSet?.update(status: status, isEmpty: isEmpty, shouldForcedDisplay: shouldForcedDisplay) + + mj_header?.endRefreshing() + switch status { + case .invalidData: // 无效的数据 + mj_footer?.endRefreshing() + case .hasMoreData: // 还有更多数据 + mj_footer?.endRefreshing() + mj_footer?.isHidden = false + case .noMoreData: // 没有更多数据 + mj_footer?.endRefreshingWithNoMoreData() + mj_footer?.isHidden = false + } + // 数据为空,隐藏footer + if isEmpty { + mj_footer?.isHidden = true + } + } +} + +public extension MJRefreshHeader { + func addFeedbackGenerator() { + rx.observeWeakly(MJRefreshState.self, "state").subscribe(onNext: { state in + guard state == .pulling else { return } + if #available(iOS 10.0, *) { + let generator = UIImpactFeedbackGenerator(style: .medium) + generator.impactOccurred() + } + }).disposed(by: rx.disposeBag) + } +} diff --git a/QuickLocation/UIKit/HUD/DLHUD.swift b/QuickLocation/UIKit/HUD/DLHUD.swift new file mode 100644 index 00000000..58cb98a1 --- /dev/null +++ b/QuickLocation/UIKit/HUD/DLHUD.swift @@ -0,0 +1,535 @@ +// +// File.swift +// JHSDK +// +// Created by osell on 2023/3/24. +// + +import UIKit + +// MARK: - DLHUD +/// DL通用Loading/Toast +@objcMembers +public class DLHUD: NSObject { + /// 是否显示HUD + public static var isShowing: Bool { DLHUDView.shared.alpha == 1 } + + /// 显示Loading + /// - Parameters: + /// - text: 提示文本 + /// - interaction: 是否可以Loading外区域交互,默认true + public static func showLoading(text: String? = nil, + inView: UIView? = nil, + completion: (() -> Void)? = nil) { + DLHUDView.shared.setupHUD(text: text, + style: .loading, + inView: inView) + } + + /// 显示HUD + /// - Parameters: + /// - text: 提示文本 + /// - interaction: 是否可以Loading外区域交互,默认true + public static func showInfo(text: String, + interaction: Bool = true, + inView: UIView? = nil, + completion: (() -> Void)? = nil) { + DLHUDView.shared.setupHUD(text: text, + style: .info, + interaction: interaction, + inView: inView) + let delay = Double(text.count) * 0.03 + 1.25 + DLHUDView.shared.dismissHUD(delay: delay, completion: completion) + } + + /// 成功HUD + /// - Parameter text: 提示文本 + public static func showSuccess(text: String? = nil, + inView: UIView? = nil, + completion: (() -> Void)? = nil) { + DLHUDView.shared.setupHUD(text: text, + style: .success, + interaction: true, + inView: inView) + + let text = text ?? "" + let delay = Double(text.count) * 0.03 + 1.25 + DLHUDView.shared.dismissHUD(delay: delay, completion: completion) + } + + /// 失败HUD + /// - Parameter text: 提示文本 + public static func showError(text: String? = nil, + inView: UIView? = nil, + completion: (() -> Void)? = nil) { + DLHUDView.shared.setupHUD(text: text, + style: .error, + interaction: true, + inView: inView) + let text = text ?? "" + let delay = Double(text.count) * 0.03 + 1.25 + DLHUDView.shared.dismissHUD(delay: delay, completion: completion) + } + + /// 显示进度HUD + /// - Parameters: + /// - text: 提示文本 + /// - progress: 进度,0 ~ 1.0 + public static func showProgress(text: String? = nil, + progress: CGFloat, + inView: UIView? = nil, + completion: (() -> Void)? = nil) { + + if progress >= 0 && progress <= 1 { + DLHUDView.shared.setupHUD(text: text, + style: .progress(progress: progress), + inView: inView) + } + + if progress >= 1 || progress < 0 { + DLHUDView.shared.dismissHUD(completion: completion) + } + } + + /// 隐藏HUD + public static func dismiss(delay: TimeInterval = 0, + completion: (() -> Void)? = nil) { + DLHUDView.shared.dismissHUD(delay: delay, completion: completion) + } + +} + +// MARK: - DLHUDConfig +@objcMembers +public class DLHUDConfig { + /// 单例 + public static let shared = DLHUDConfig() + /// HUD背景样式 + public var backgroundStyle: UIBarStyle = .black + /// HUD文字颜色 + public var textColor: UIColor = .white + /// HUD文字大小 + public var textFont: UIFont = .boldSystemFont(ofSize: 13) + /// HUD Progress颜色 + public var progress: UIColor = .white + /// Success图标 + public var successImage: UIImage? + /// Error图标 + public var errorImage: UIImage? + + private init() {} +} + +// MARK: - DLHUDView +fileprivate class DLHUDView: UIView { + + // HUD样式 + enum Style { + case info, // 默认 + loading, // loading + success, // 成功 + error, // 错误 + progress(progress: CGFloat) // 进度 + } + + /// 单例 + static let shared = DLHUDView() + + var completeBlock: (() -> Void)? + + /// 提示文字 + lazy var textLabel: UILabel = { + let label = UILabel() + label.textAlignment = .center + label.baselineAdjustment = .alignCenters + label.numberOfLines = 0 + label.font = UIFont.systemFont(ofSize: 15) + return label + }() + + /// 图片 + lazy var iconImageView: UIImageView = { + let view = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 60)) + view.contentMode = .scaleAspectFit + return view + }() + + /// 进度view + lazy var progressView: DLProgressView = { + let view = DLProgressView() + return view + }() + + /// 动画View + lazy var animationView: UIView = { + let view = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60)) + return view + }() + + /// hudToolBar + lazy var hudToolBar: UIToolbar = { + let view = UIToolbar() + view.isTranslucent = true + view.clipsToBounds = true + view.layer.cornerRadius = 8 + view.layer.masksToBounds = true + return view + }() + + /// 背景 + lazy var backgroundView: UIView = { + let view = UIView() + return view + }() + + /// 定时器 + private var timer: Timer? + + convenience private init() { + self.init(frame: UIScreen.main.bounds) + alpha = 0 + } + + override private init(frame: CGRect) { + super.init(frame: frame) + } + + required internal init?(coder: NSCoder) { + super.init(coder: coder) + } +} + +// MARK: - Method +private extension DLHUDView { + + /// 设置HUD + /// - Parameters: + /// - text: 文字 + /// - style: 样式 + /// - interaction: 是否可以交互 + /// - isAutoHide: 是否自动隐藏 + /// - inView: 在View显示 + func setupHUD(text: String? = nil, + style: DLHUDView.Style, + interaction: Bool = false, + inView: UIView? = nil) { + DispatchQueue.main.async { + self.hudToolBar.layer.removeAllAnimations() + self.setupBackgoundView(with: interaction, in: inView) + self.setupToolBar() + self.removeOtherView(with: style) + switch style { + case .progress(let progress): + self.setupTextLabel(with: text) + self.setupProgressView(with: progress) + case .error, .success: + self.setupImageView(with: style) + self.setupTextLabel(with: text) + case .loading: + self.setupLoadingView() + self.setupTextLabel(with: text) + default: + self.setupTextLabel(with: text) + } + // 设置 + self.setupSize(with: style) + self.displayHUD() + } + } + + /// 显示HUD + func displayHUD() { + + synchronized(self.hudToolBar) { + if self.alpha == 0 { + self.alpha = 1 + self.hudToolBar.alpha = 0 + self.hudToolBar.transform = CGAffineTransform(scaleX: 0.3, y: 0.3) + UIView.animate(withDuration: 0.15, delay: 0, options: [.allowUserInteraction, .curveEaseIn]) { + self.hudToolBar.alpha = 1 + self.hudToolBar.transform = CGAffineTransform.identity + } + } + } + } + + /// 隐藏HUD + func dismissHUD(delay: TimeInterval = 0, completion: (() -> Void)? = nil) { + if timer != nil { + timer?.invalidate() + timer = nil + } + self.timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { [weak self] _ in + guard let self = self else { return } + DispatchQueue.main.async { +// synchronized(self.hudToolBar) { + if self.alpha == 1 { + UIView.animate(withDuration: 0.15, delay: 0, options: [.allowUserInteraction, .curveEaseIn]) { + self.hudToolBar.transform = CGAffineTransform(scaleX: 0.3, y: 0.3) + self.hudToolBar.alpha = 0 + } completion: { _ in + self.iconImageView.removeFromSuperview() + self.animationView.removeFromSuperview() + self.progressView.removeFromSuperview() + self.progressView.setProgress(0) + self.hudToolBar.transform = CGAffineTransform.identity + self.hudToolBar.removeFromSuperview() + self.backgroundView.removeFromSuperview() + self.textLabel.removeFromSuperview() + self.alpha = 0 + self.removeFromSuperview() + completion?() + } + } +// } + } + } + #if swift(>=4.2) + RunLoop.current.add(self.timer!, forMode: .common) + #else + RunLoop.current.add(self.timer!, forMode: .commonModes) + #endif + } +} + +// MARK: - Private Method +private extension DLHUDView { + /// 设置背景view + func setupBackgoundView(with interaction: Bool, in superView: UIView? = nil) { + guard let superTempView = superView ?? UIApplication.keyWindow else { return } + + if backgroundView.superview == nil || backgroundView.superview != superTempView { + backgroundView.removeFromSuperview() + backgroundView.frame = superTempView.bounds + superTempView.addSubview(backgroundView) + } + backgroundView.backgroundColor = .clear + backgroundView.isUserInteractionEnabled = !interaction + } + + /// 设置hudToolBar + func setupToolBar() { + if hudToolBar.superview == nil { + hudToolBar.frame = .zero + backgroundView.addSubview(hudToolBar) + } + hudToolBar.barStyle = DLHUDConfig.shared.backgroundStyle + hudToolBar.backgroundColor = UIColor.white + } + + /// 设置Text + func setupTextLabel(with text: String?) { + if textLabel.superview == nil { + hudToolBar.addSubview(textLabel) + } + textLabel.text = text + textLabel.textColor = DLHUDConfig.shared.textColor + textLabel.font = DLHUDConfig.shared.textFont + textLabel.isHidden = !(text?.isEmpty != true) + } + + /// 设置自定义View + func setupCustomView(with view: UIView) { + if view.superview == nil { + hudToolBar.addSubview(view) + } + } + + /// 设置Progress + /// - Parameter progress: CGFloat + func setupProgressView(with progress: CGFloat) { + if progressView.superview == nil { + progressView.frame = CGRect(x: 0, y: 0, width: 60, height: 60) + hudToolBar.addSubview(progressView) + } + progressView.setProgress(progress) + progressView.color = DLHUDConfig.shared.progress + } + + /// 设置图标 + func setupImageView(with style: DLHUDView.Style) { + + if iconImageView.superview == nil { + hudToolBar.addSubview(iconImageView) + } + switch style { + case .success: + iconImageView.image = DLHUDConfig.shared.successImage ?? UIImage(named: "hud_success") + case .error: + iconImageView.image = DLHUDConfig.shared.errorImage ?? UIImage(named: "hud_error") + default: + iconImageView.image = nil + } + } + + /// 设置Loading + func setupLoadingView() { + animationView.subviews.forEach { $0.removeFromSuperview() } + + if animationView.superview == nil { + hudToolBar.addSubview(animationView) + } + + let spinner = UIActivityIndicatorView(style: .whiteLarge) + spinner.frame = animationView.bounds + spinner.color = .lightGray + spinner.hidesWhenStopped = true + spinner.startAnimating() + animationView.addSubview(spinner) + } + + /// 移除非当前类型view + /// - Parameter style: Style + func removeOtherView(with style: DLHUDView.Style) { + switch style { + case .info: + animationView.removeFromSuperview() + progressView.removeFromSuperview() + iconImageView.removeFromSuperview() + textLabel.removeFromSuperview() + case .loading: + progressView.removeFromSuperview() + iconImageView.removeFromSuperview() + textLabel.removeFromSuperview() + case .success, .error: + animationView.removeFromSuperview() + progressView.removeFromSuperview() + textLabel.removeFromSuperview() + case .progress: + animationView.removeFromSuperview() + iconImageView.removeFromSuperview() + textLabel.removeFromSuperview() + } + + } + + /// 设置Hud的size + /// - Parameter style: Style + func setupSize(with style: DLHUDView.Style) { + + var hudWidth: CGFloat = 120 + var hudHeight: CGFloat = 120 + let screenSize = backgroundView.superview?.frame.size ?? UIScreen.main.bounds.size + let maxWidth = min(screenSize.width, screenSize.height) - 80 + if let text = textLabel.text, !text.isEmpty { + var textRect = text.boundingRect(with: CGSize(width: maxWidth, height: screenSize.height * 0.65), + options: .usesLineFragmentOrigin, + attributes: [NSAttributedString.Key.font : DLHUDConfig.shared.textFont], + context: nil) + hudWidth = ceil(textRect.size.width) + 40 + hudHeight = ceil(textRect.size.height) + + if hudWidth < 120 { hudWidth = 120 } + + textRect.origin.x = (hudWidth - textRect.size.width) / 2 + switch style { + case .info: + hudHeight = hudHeight + 40 + textRect.origin.y = (hudHeight - textRect.size.height) / 2 + default: + textRect.origin.y = 90 + hudHeight = hudHeight + 110 + } + + textLabel.frame = textRect + } + + hudToolBar.bounds = CGRect(origin: .zero, size: CGSize(width: hudWidth, height: hudHeight)) + + let centerX = hudWidth / 2 + var centerY = hudWidth / 2 + + if textLabel.text != nil { centerY = 50 } + + progressView.center = CGPoint(x: centerX, y: centerY) + animationView.center = CGPoint(x: centerX, y: centerY) + iconImageView.center = CGPoint(x: centerX, y: centerY) + + hudToolBar.center = CGPoint(x: screenSize.width / 2, y: screenSize.height / 2) + } + +} + +// MARK: - DLProgressView +public class DLProgressView: UIView { + + public var color: UIColor = .white { + didSet { setupLayers() } + } + private var progress: CGFloat = 0 + + private var layerCircle = CAShapeLayer() + private var layerProgress = CAShapeLayer() + private var labelPercentage: UILabel = UILabel() + + convenience init(_ color: UIColor) { + + self.init(frame: .zero) + self.color = color + } + + required init?(coder: NSCoder) { + + super.init(coder: coder) + } + + override init(frame: CGRect) { + + super.init(frame: frame) + } + + public override func draw(_ rect: CGRect) { + + super.draw(rect) + setupLayers() + } + + func setupLayers() { + + subviews.forEach { $0.removeFromSuperview() } + layer.sublayers?.forEach { $0.removeFromSuperlayer() } + + let width = frame.size.width + let height = frame.size.height + + let center = CGPoint(x: width/2, y: height/2) + let radiusCircle = width / 2 + let radiusProgress = width / 2 + + let pathCircle = UIBezierPath(arcCenter: center, radius: radiusCircle, startAngle: -0.5 * .pi, endAngle: 1.5 * .pi, clockwise: true) + let pathProgress = UIBezierPath(arcCenter: center, radius: radiusProgress, startAngle: -0.5 * .pi, endAngle: 1.5 * .pi, clockwise: true) + + layerCircle.path = pathCircle.cgPath + layerCircle.fillColor = UIColor.clear.cgColor + layerCircle.lineWidth = 3 + layerCircle.strokeColor = color.withAlphaComponent(0.2).cgColor + + layerProgress.path = pathProgress.cgPath + layerProgress.fillColor = UIColor.clear.cgColor + layerProgress.lineWidth = 4 + layerProgress.strokeColor = color.cgColor + layerProgress.strokeEnd = 0 + + layer.addSublayer(layerCircle) + layer.addSublayer(layerProgress) + + labelPercentage.frame = self.bounds + labelPercentage.textColor = color + labelPercentage.textAlignment = .center + addSubview(labelPercentage) + } + + public func setProgress(_ value: CGFloat, duration: TimeInterval = 0.2) { + + let animation = CABasicAnimation(keyPath: "strokeEnd") + animation.duration = duration + animation.fromValue = progress + animation.toValue = value + animation.fillMode = .both + animation.isRemovedOnCompletion = false + layerProgress.add(animation, forKey: "animation") + + progress = value + labelPercentage.text = "\(Int(value*100))%" + } +} diff --git a/QuickLocation/UIKit/HUD/HUD.swift b/QuickLocation/UIKit/HUD/HUD.swift new file mode 100644 index 00000000..425deaf2 --- /dev/null +++ b/QuickLocation/UIKit/HUD/HUD.swift @@ -0,0 +1,94 @@ +// +// HUD.swift +// MTViewer +// +// Created by XUXIAOTENG on 17/05/2017. +// Copyright © 2017 GXM. All rights reserved. +// + +import UIKit + +public class HUD: UIView { + + public var containerView: UIView? + public var offset: CGFloat = 0 + + let activityIndicatorView: UIActivityIndicatorView = { + let activity = UIActivityIndicatorView(style: .white) + activity.color = UIColor.gray + return activity + }() + + public convenience init(container view: UIView) { + self.init() + containerView = view + } + + override public func layoutSubviews() { + super.layoutSubviews() + activityIndicatorView.center = CGPoint(x: self.center.x, y: self.center.y - offset) + } + + public func show() { + if let view = containerView { + if !view.subviews.contains(self) { + self.alpha = 1.0 + self.frame.origin = CGPoint.zero + self.frame.size = view.frame.size + self.autoresizingMask = [.flexibleHeight, .flexibleWidth] + view.addSubview(self) + + self.addSubview(activityIndicatorView) + activityIndicatorView.center = CGPoint(x: self.center.x, y: self.center.y - offset) + activityIndicatorView.autoresizingMask = [.flexibleHeight, .flexibleWidth] + } + activityIndicatorView.startAnimating() + } + } + + public func hide() { + UIView.animate(withDuration: 0.3, animations: { + self.alpha = 0.0 + }, completion: { _ in + self.activityIndicatorView.stopAnimating() + self.removeFromSuperview() + }) + } + + public class func show(inView view: UIView? = nil, color: UIColor? = nil, offset: CGFloat? = nil) { + let view: UIView = view ?? UIApplication.keyWindow! + let hud = HUD(container: view) + if color != nil { + hud.activityIndicatorView.color = color + } + if let offset = offset { + hud.offset = offset + } + hud.show() + } + + public class func show(inView view: UIView? = nil, interaction: Bool) { + let view: UIView = view ?? UIApplication.keyWindow! + let hud = HUD(container: view) + hud.isUserInteractionEnabled = !interaction + hud.show() + } + + public class func hide(forView view: UIView? = nil, immediate: Bool = false) { + let view: UIView = view ?? UIApplication.keyWindow! + for subView in view.subviews where subView is HUD { + if let hud = subView as? HUD { + if immediate { + hud.removeFromSuperview() + } else { + UIView.animate(withDuration: 0.3, animations: { + hud.alpha = 0.0 + }, completion: { _ in + hud.removeFromSuperview() + }) + } + } + } + } + +} diff --git a/QuickLocation/UIKit/HUD/ProgressHUD.swift b/QuickLocation/UIKit/HUD/ProgressHUD.swift new file mode 100644 index 00000000..950330fc --- /dev/null +++ b/QuickLocation/UIKit/HUD/ProgressHUD.swift @@ -0,0 +1,215 @@ +// +// ProgressHUD.swift +// JiuLaiBao +// +// Created by 霹雳火 on 2018/8/15. +// Copyright © 2018 GuoXiaoMei. All rights reserved. +// + +import UIKit +import MBProgressHUD + +public class ProgressHUD: NSObject { + + public enum HUDType { + case loading(status: String?) + case progress(progress: Float, status: String?) + case info(status: String?) + case success(status: String?) + case error(status: String?) + case dismiss + case dismissImmediate + case dismissDelay(delay: TimeInterval) + case dismissDelayAndCompletion(delay: TimeInterval, completion: ProgressHUD.ProgressHUDDismissCompletion?) + case dismissCompletion(completion: ProgressHUD.ProgressHUDDismissCompletion?) + } + + public typealias ProgressHUDDismissCompletion = (() -> Void) + + static public var successImage = UIImage(named: "ProgressHUD/success")! + static public var errorImage = UIImage(named: "ProgressHUD/error")! + static public var infoImage = UIImage(named: "ProgressHUD/info")! + static public let ProgressHUDUndefinedProgress: Float = -1 + static public var minimumDismissTimeInterval: TimeInterval = 1 + static public var maximumDismissTimeInterval: TimeInterval = 3 + + static public func createProgressHUD(for view: UIView) -> MBProgressHUD { + let hud = MBProgressHUD.showAdded(to: view, animated: true) + hud.contentColor = .white + hud.animationType = .fade + hud.removeFromSuperViewOnHide = true + hud.isUserInteractionEnabled = true + + hud.bezelView.color = UIColor.black.withAlphaComponent(0.53) + hud.bezelView.style = .solidColor + + hud.label.numberOfLines = 0 + hud.detailsLabel.font = UIFont.boldSystemFont(ofSize: 16) + return hud + } + + static public func findProgressHUD(for view: UIView) -> MBProgressHUD? { + let hud = MBProgressHUD(view: view) + hud.isUserInteractionEnabled = true + return hud + } + + static public func frontWindow() -> UIWindow { + let mainWindow = UIApplication.shared.delegate?.window + return mainWindow!! + } + + // MARK: show/hide method + @discardableResult static public func show(withStatus status: String? = nil, + addedTo view: UIView? = nil) -> MBProgressHUD { + return showProgress(progress: ProgressHUDUndefinedProgress, status: status, addedTo: view) + } + + @discardableResult static public func showProgress(progress: Float, + status: String? = nil, + addedTo view: UIView? = nil, + offset: CGPoint = .zero) -> MBProgressHUD { + let hudView: MBProgressHUD + let forView = view ?? frontWindow() + if let findHUD = findProgressHUD(for: forView) { + hudView = findHUD + } else { + hudView = createProgressHUD(for: forView) + } + + if progress == ProgressHUDUndefinedProgress { + hudView.mode = .indeterminate + } else { + hudView.mode = .annularDeterminate + hudView.progress = progress + } + hudView.detailsLabel.text = status + hudView.isUserInteractionEnabled = true + hudView.offset = offset + forView.bringSubviewToFront(hudView) + return hudView + } + + @discardableResult static public func show(_ image: UIImage, + status: String? = nil, + addedTo view: UIView? = nil, + offset: CGPoint = .zero) -> MBProgressHUD { + let displayInterval = displayDuration(for: status) + let hudView: MBProgressHUD + let forView = view ?? frontWindow() + if let findHUD = findProgressHUD(for: forView) { + hudView = findHUD + } else { + hudView = createProgressHUD(for: forView) + } + hudView.mode = .customView + hudView.customView = UIImageView(image: image) + hudView.detailsLabel.text = status + hudView.offset = offset + hudView.isUserInteractionEnabled = false + forView.bringSubviewToFront(hudView) + hudView.hide(animated: true, afterDelay: displayInterval) + return hudView + } + + // MARK: show/hide method + @discardableResult static public func show(withStatus status: String? = nil, + inController controller: UIViewController?) -> MBProgressHUD { + return showProgress(progress: ProgressHUDUndefinedProgress, status: status, inController: controller) + } + + @discardableResult static public func showProgress(progress: Float, + status: String? = nil, + inController controller: UIViewController?) -> MBProgressHUD { + if let controller = controller { + if controller.fd_prefersNavigationBarHidden { + return showProgress(progress: progress, status: status, addedTo: controller.view) + } else { + let navigatorHeight = UIApplication.shared.statusBarFrame.size.height + 44.0 + let offset = CGPoint(x: 0, y: -navigatorHeight / 2.0) + return showProgress(progress: progress, status: status, addedTo: controller.view, offset: offset) + } + } else { + return showProgress(progress: progress, status: status, addedTo: nil) + } + } + + @discardableResult static public func showInfo(withStatus status: String? = nil, + addedTo view: UIView? = nil) -> MBProgressHUD { + return show(infoImage, status: status, addedTo: view) + } + + @discardableResult static public func showSuccess(withStatus status: String? = nil, + addedTo view: UIView? = nil) -> MBProgressHUD { + return show(successImage, status: status, addedTo: view) + } + + @discardableResult static public func showError(withStatus status: String? = nil, + addedTo view: UIView? = nil) -> MBProgressHUD { + return show(errorImage, status: status, addedTo: view) + } + + @discardableResult static public func showInfo(withStatus status: String? = nil, + inController controller: UIViewController?) -> MBProgressHUD { + return show(infoImage, status: status, inController: controller) + } + + @discardableResult static public func showSuccess(withStatus status: String? = nil, + inController controller: UIViewController?) -> MBProgressHUD { + return show(successImage, status: status, inController: controller) + } + + @discardableResult static public func showError(withStatus status: String? = nil, + inController controller: UIViewController?) -> MBProgressHUD { + return show(errorImage, status: status, inController: controller) + } + + @discardableResult static public func show(_ image: UIImage, + status: String? = nil, + inController controller: UIViewController?) -> MBProgressHUD { + if let controller = controller { + if controller.fd_prefersNavigationBarHidden { + return show(image, status: status, addedTo: controller.view) + } else { + let navigatorHeight = UIApplication.shared.statusBarFrame.size.height + 44.0 + let offset = CGPoint(x: 0, y: -navigatorHeight / 2.0) + return show(image, status: status, addedTo: controller.view, offset: offset) + } + } else { + return show(image, status: status, addedTo: controller?.view) + } + } + + static public func dismiss(withDelay delay: TimeInterval = 0, + immediate: Bool = false, + forView view: UIView? = nil, + completion: ProgressHUDDismissCompletion? = nil) { + let forView = view ?? frontWindow() + let hudView = findProgressHUD(for: forView) + hudView?.completionBlock = completion + if immediate { + hudView?.hide(animated: false) + } else { + hudView?.hide(animated: true, afterDelay: delay) + } + } + + static public func dismiss(withDelay delay: TimeInterval = 0, + immediate: Bool = false, + forController controller: UIViewController?, + completion: ProgressHUDDismissCompletion? = nil) { + let forView = controller?.view ?? frontWindow() + let hudView = findProgressHUD(for: forView) + hudView?.completionBlock = completion + if immediate { + hudView?.hide(animated: false) + } else { + hudView?.hide(animated: true, afterDelay: delay) + } + } + + static public func displayDuration(for string: String?) -> TimeInterval { + let minimum = Double.maximum(Double(string?.count ?? 0) * 0.06 + 0.5, minimumDismissTimeInterval) + return Double.minimum(minimum, maximumDismissTimeInterval) + } +} diff --git a/QuickLocation/UIKit/JJPageControl.swift b/QuickLocation/UIKit/JJPageControl.swift new file mode 100644 index 00000000..b9556999 --- /dev/null +++ b/QuickLocation/UIKit/JJPageControl.swift @@ -0,0 +1,466 @@ +// +// JJPageControl.swift +// JJPageControl +// +// https://github.com/zxhkit/JJPageControl +// Created by xuanhe on 2022/9/1. +// + +import UIKit + +enum JJPageControlAliment { + case Center + case Left + case Right +} + +protocol JJPageControlDelegate { + func jj_pageControlClick(pageControl: JJPageControl, index: Int) +} + +class JJPageControl: UIControl { + + /// 闭包点击事件 + var clickPointClosure: ((_ num : Int) -> Void)? + + /// 当前点的大小 + var currentPointSize: CGSize = CGSize(width: 6, height: 6) { + didSet{ + assert((currentPointSize.width >= 1 && currentPointSize.height >= 1), "Parameter value is not valid. currentPointSize must be greater than 1.") + if numberOfPages > 0 { + createPointView() + } + } + } + /// 其他点的大小 + var otherPointSize: CGSize = CGSize(width: 6, height: 6) { + didSet{ + assert((otherPointSize.width >= 1 && otherPointSize.height >= 1), "Parameter value is not valid. otherPointSize must be greater than 1.") + if numberOfPages > 0 { + createPointView() + } + } + } + /// 点-切圆角 + var pointCornerRadius:CGFloat = 3 { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + /// 位置 + var pageAliment: JJPageControlAliment = .Center { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + /// 分页数量 + var numberOfPages: Int = 0 { + didSet{ + if oldValue != numberOfPages { + createPointView() + } + } + } + + /// 当前点所在下标 + var currentPage: Int = 0 { + didSet{ + if currentPage >= 0 { + exchangePointView(oldValue, currentPage) + }else{ + currentPage = 0 + } + } + } + ///点的间距 + var controlSpacing: CGFloat = 8 { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + ///左右间距 + var leftAndRightSpacing: CGFloat = 10 { + didSet{ + if leftAndRightSpacing < 0 { + leftAndRightSpacing = 0 + }else{ + if numberOfPages > 0 { + createPointView() + } + } + } + } + /// 其他点未选中颜色 + var otherColor: UIColor = .gray { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + /// 当前点颜色 + var currentColor: UIColor = .orange { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + /// 其他点背景图片 + var otherBkImage: UIImage? { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + /// 当前点背景图片 + var currentBkImage: UIImage? { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + ///当前选中点的layer宽 + var currentLayerBorderWidth: CGFloat = 1 { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + + ///其他点的layer宽 + var otherLayerBorderWidth: CGFloat = 1 { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + + ///当前选中点的layer颜色 + var currentLayerBorderColor: UIColor? { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + ///其他选中点的layer颜色 + var otherLayerBorderColor: UIColor? { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + + + /// 当只有一个点的时候是否隐藏 + var isHidesForSinglePage = true { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + /// 是否可以点击 默认不可以点击 + var isCanClickPoint = false { + didSet{ + if numberOfPages > 0 { + createPointView() + } + } + } + + /// 重写设置frame + override var frame:CGRect { + didSet{ + let mainWidth = (CGFloat(numberOfPages) - 1) * otherPointSize.width + (CGFloat(numberOfPages) - 1) * controlSpacing + currentPointSize.width + leftAndRightSpacing * 2 + + if frame.width < mainWidth { + frame.size.width = mainWidth + } + let max_height = max(otherPointSize.height, currentPointSize.height) + if frame.height < max_height { + frame.size.height = max_height + } + createPointView() + } + } + + /// 协议代理 + var delegate:JJPageControlDelegate? + + private var dots = [UIImageView]() + + /// 创建视图 + private func createPointView() { + /// 先清除视图 + clearView() + + if numberOfPages <= 0 { + return + } + + if isHidesForSinglePage == true ,numberOfPages == 1{ + return + } + //居中控件 + var startX:CGFloat = 0 + var startY_current:CGFloat = 0 + var startY_other:CGFloat = 0 + + + let mainWidth = (CGFloat(numberOfPages) - 1) * otherPointSize.width + (CGFloat(numberOfPages) - 1) * controlSpacing + currentPointSize.width + leftAndRightSpacing * 2 + 1 + if frame.width < mainWidth { + frame.size.width = mainWidth + }else{ + if pageAliment == .Left { + startX = leftAndRightSpacing + } else if pageAliment == .Center { + startX = (self.frame.size.width - mainWidth)/2.0 + } else { + startX = frame.width - mainWidth + } + } + + let max_height = max(otherPointSize.height, currentPointSize.height) + if frame.height < max_height { + frame.size.height = max_height + startY_current = max_height - currentPointSize.height + startY_other = max_height - otherPointSize.height + + } else { + startY_current = (frame.height - max_height)/2.0 + (max_height - currentPointSize.height) + startY_other = (frame.height - max_height)/2.0 + (max_height - otherPointSize.height) + } + + for page in 0..= 0 { + currentPage = index + delegate?.jj_pageControlClick(pageControl: self, index: index) + if let closure = self.clickPointClosure { + closure(index) + } + } + } + } + + + + func clearView() { + // subviews.forEach { subView in + // subView.removeFromSuperview() + // } + + subviews.forEach { $0.removeFromSuperview()} + dots.removeAll() + } + + func exchangePointView(_ oldPage: Int, _ newPage: Int) { + if oldPage == newPage { + return + } + if oldPage > dots.count { + return + } + if newPage > dots.count { + return + } + + + let oldDot = dots[oldPage] + let oldFrame = oldDot.frame + + let newDot = dots[newPage] + let newFrame = newDot.frame + + newDot.image = currentBkImage + if let _ = currentBkImage { + newDot.backgroundColor = .clear + }else{ + newDot.backgroundColor = currentColor + } + + oldDot.image = otherBkImage + if let _ = otherBkImage { + oldDot.backgroundColor = .clear + }else{ + oldDot.backgroundColor = otherColor + } + + if self.currentLayerBorderColor != nil { + newDot.layer.borderColor = self.currentLayerBorderColor?.cgColor + newDot.layer.borderWidth = self.currentLayerBorderWidth + }else{ + newDot.layer.borderWidth = 0 + } + + if self.otherLayerBorderColor != nil { + oldDot.layer.borderColor = self.otherLayerBorderColor?.cgColor + oldDot.layer.borderWidth = self.otherLayerBorderWidth + }else{ + oldDot.layer.borderWidth = 0 + } + + var oldMinx = oldFrame.minX + var newMinx = newFrame.minX + + UIView.animate(withDuration: 0.25) { + if newPage < oldPage { + oldMinx = oldMinx + (self.currentPointSize.width - self.otherPointSize.width) + } + oldDot.frame = CGRect(x: oldMinx, y: newFrame.minY, width: self.otherPointSize.width, height: self.otherPointSize.height) + + if newPage > oldPage { + newMinx = newMinx - (self.currentPointSize.width - self.otherPointSize.width) + } + newDot.frame = CGRect(x: newMinx, y: oldFrame.minY, width: self.currentPointSize.width, height: self.currentPointSize.height) + + + if newPage - oldPage > 1 { //往右滑动 + for index in (oldPage+1).. oldPage { + newMinx = newMinx - (self.currentPointSize.width - self.otherPointSize.width) + } + newDot.frame = CGRect(x: newMinx, y: oldFrame.minY, width: self.currentPointSize.width, height: self.currentPointSize.height) + + + if newPage - oldPage > 1 { //往右滑动 + for index in (oldPage+1).. + +NS_ASSUME_NONNULL_BEGIN + +/** + The parallac header mode. + */ +typedef NS_ENUM(NSInteger, MXParallaxHeaderMode) { + /** + The option to scale the content to fill the size of the header. Some portion of the content may be clipped to fill the header’s bounds. + */ + MXParallaxHeaderModeFill = 0, + /** + The option to scale the content to fill the size of the header and aligned at the top in the header's bounds. + */ + MXParallaxHeaderModeTopFill, + /** + The option to center the content aligned at the top in the header's bounds. + */ + MXParallaxHeaderModeTop, + /** + The option to center the content in the header’s bounds, keeping the proportions the same. + */ + MXParallaxHeaderModeCenter, + /** + The option to center the content aligned at the bottom in the header’s bounds. + */ + MXParallaxHeaderModeBottom +}; + +@protocol MXParallaxHeaderDelegate; + +/** + The MXParallaxHeader class represents a parallax header for UIScrollView. + */ +@interface MXParallaxHeader : NSObject + +/** + The content view on top of the UIScrollView's content. + */ +@property (nonatomic,readonly) UIView *contentView; + +/** + Delegate instance that adopt the MXScrollViewDelegate. + */ +@property (nonatomic,weak,nullable) IBOutlet id delegate; + +/** + The header's view. + */ +@property (nonatomic,strong,nullable) IBOutlet UIView *view; + +/** + The header's default height. 0 by default. + */ +@property (nonatomic) IBInspectable CGFloat height; + +/** + The header's minimum height while scrolling up. 0 by default. + */ +@property (nonatomic) IBInspectable CGFloat minimumHeight; + +/** + The parallax header behavior mode. + */ +@property (nonatomic) MXParallaxHeaderMode mode; + +/** + The parallax header progress value. + */ +@property (nonatomic,readonly) CGFloat progress; + +/** + Loads a `view` from the nib file in the specified bundle. + + @param name The name of the nib file, without any leading path information. + @param bundleOrNil The bundle in which to search for the nib file. If you specify nil, this method looks for the nib file in the main bundle. + @param optionsOrNil A dictionary containing the options to use when opening the nib file. For a list of available keys for this dictionary, see NSBundle UIKit Additions. + */ +- (void)loadWithNibName:(NSString *)name bundle:(nullable NSBundle *)bundleOrNil options:(nullable NSDictionary *)optionsOrNil; + +@end + +/** + The method declared by the MXParallaxHeaderDelegate protocol allow the adopting delegate to respond to scoll from the MXParallaxHeader class. + */ +@protocol MXParallaxHeaderDelegate + +@optional + +/** + Tells the header view that the parallax header did scroll. + The view typically implements this method to obtain the change in progress from parallaxHeaderView. + + @param parallaxHeader The parallax header that scrolls. + */ +- (void)parallaxHeaderDidScroll:(MXParallaxHeader *)parallaxHeader; + +@end + +DEPRECATED_MSG_ATTRIBUTE("Use the MXParallaxHeader's delegate property instead.") +@protocol MXParallaxHeader +@end + +/** + A UIScrollView category with a MXParallaxHeader. + */ +@interface UIScrollView (MXParallaxHeader) + +/** + The parallax header. + */ +@property (nonatomic, strong) IBOutlet MXParallaxHeader *parallaxHeader; + +@end + +NS_ASSUME_NONNULL_END diff --git a/QuickLocation/UIKit/MXParallaxHeader/MXParallaxHeader.m b/QuickLocation/UIKit/MXParallaxHeader/MXParallaxHeader.m new file mode 100644 index 00000000..3fc62e1e --- /dev/null +++ b/QuickLocation/UIKit/MXParallaxHeader/MXParallaxHeader.m @@ -0,0 +1,289 @@ +// MXParallaxHeader.m +// +// Copyright (c) 2019 Maxime Epain +// +// 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 +#import "MXParallaxHeader.h" + +@interface MXParallaxView : UIView +@property (nonatomic,weak) MXParallaxHeader *parent; +@end + +@implementation MXParallaxView + +static void * const kMXParallaxHeaderKVOContext = (void*)&kMXParallaxHeaderKVOContext; + +- (void)willMoveToSuperview:(UIView *)newSuperview { + if ([self.superview isKindOfClass:[UIScrollView class]]) { + [self.superview removeObserver:self.parent forKeyPath:NSStringFromSelector(@selector(contentOffset)) context:kMXParallaxHeaderKVOContext]; + } +} + +- (void)didMoveToSuperview{ + if ([self.superview isKindOfClass:[UIScrollView class]]) { + [self.superview addObserver:self.parent + forKeyPath:NSStringFromSelector(@selector(contentOffset)) + options:NSKeyValueObservingOptionNew + context:kMXParallaxHeaderKVOContext]; + } +} + +@end + +@interface MXParallaxHeader () +@property (nonatomic, weak) UIScrollView *scrollView; + +@property (nonatomic, strong) NSLayoutConstraint *positionConstraint; +@property (nonatomic, strong) NSLayoutConstraint *heightConstraint; +@end + +@implementation MXParallaxHeader { + BOOL _isObserving; +} + +@synthesize contentView = _contentView; + +#pragma mark Properties + +- (UIView *)contentView { + if (!_contentView) { + MXParallaxView *contentView = [MXParallaxView new]; + contentView.parent = self; + contentView.clipsToBounds = YES; + contentView.translatesAutoresizingMaskIntoConstraints = NO; + + _heightConstraint = [contentView.heightAnchor constraintEqualToConstant:0]; + + _contentView = contentView; + } + return _contentView; +} + +- (void)setView:(UIView *)view { + if (view != _view) { + [_view removeFromSuperview]; + _view = view; + + [self updateConstraints]; + + [self.contentView layoutIfNeeded]; + + self.height = self.contentView.frame.size.height; + self.heightConstraint.constant = self.height; + self.heightConstraint.active = YES; + } +} + +- (void)setMode:(MXParallaxHeaderMode)mode { + if (_mode != mode) { + _mode = mode; + [self updateConstraints]; + } +} + +- (void)setHeight:(CGFloat)height { + if (_height != height) { + + //Adjust content inset + [self adjustScrollViewTopInset:self.scrollView.contentInset.top - _height + height]; + + _height = height; + + self.heightConstraint.constant = height; + self.heightConstraint.active = YES; + [self layoutContentView]; + } +} + +- (void)setMinimumHeight:(CGFloat)minimumHeight { + _minimumHeight = minimumHeight; + [self layoutContentView]; +} + +- (void)setScrollView:(UIScrollView *)scrollView { + if (_scrollView != scrollView) { + _scrollView = scrollView; + _isObserving = YES; + } +} + +- (void)setProgress:(CGFloat)progress { + if(_progress != progress) { + _progress = progress; + + if ([self.delegate respondsToSelector:@selector(parallaxHeaderDidScroll:)]) { + [self.delegate parallaxHeaderDidScroll:self]; + } + } +} + +- (void)loadWithNibName:(NSString *)name bundle:(nullable NSBundle *)bundleOrNil options:(nullable NSDictionary *)optionsOrNil { + UINib *nib = [UINib nibWithNibName:name bundle:bundleOrNil]; + [nib instantiateWithOwner:self options:optionsOrNil]; +} + +#pragma mark Constraints + +- (void)updateConstraints { + if (!self.view) return; + + [self.contentView removeFromSuperview]; + [self.scrollView addSubview:self.contentView]; + + [self.view removeFromSuperview]; + [self.contentView addSubview:self.view]; + + self.view.translatesAutoresizingMaskIntoConstraints = NO; + + switch (self.mode) { + case MXParallaxHeaderModeFill: + [self setFillModeConstraints]; + break; + + case MXParallaxHeaderModeTopFill: + [self setTopFillModeConstraints]; + break; + + case MXParallaxHeaderModeTop: + [self setTopModeConstraints]; + break; + + case MXParallaxHeaderModeBottom: + [self setBottomModeConstraints]; + break; + + default: + [self setCenterModeConstraints]; + break; + } + + [self setContentViewConstraints]; +} + +- (void)setCenterModeConstraints { + [self.view.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor].active = YES; + [self.view.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor].active = YES; + [self.view.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor].active = YES; + [self.view.heightAnchor constraintEqualToConstant:self.height].active = YES; +} + +- (void)setFillModeConstraints { + [self.view.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor].active = YES; + [self.view.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor].active = YES; + [self.view.topAnchor constraintEqualToAnchor:self.contentView.topAnchor].active = YES; + [self.view.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor].active = YES; +} + +- (void)setTopFillModeConstraints { + [self.view.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor].active = YES; + [self.view.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor].active = YES; + [self.view.topAnchor constraintEqualToAnchor:self.contentView.topAnchor].active = YES; + [self.view.heightAnchor constraintGreaterThanOrEqualToConstant:self.height].active = YES; + + NSLayoutConstraint *constraint = [self.view.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor]; + constraint.priority = UILayoutPriorityDefaultHigh; + constraint.active = YES; +} + +- (void)setTopModeConstraints { + [self.view.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor].active = YES; + [self.view.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor].active = YES; + [self.view.topAnchor constraintEqualToAnchor:self.contentView.topAnchor].active = YES; + [self.view.heightAnchor constraintEqualToConstant:self.height].active = YES; +} + +- (void)setBottomModeConstraints { + [self.view.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor].active = YES; + [self.view.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor].active = YES; + [self.view.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor].active = YES; + [self.view.heightAnchor constraintEqualToConstant:self.height].active = YES; +} + +- (void)setContentViewConstraints { + [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor].active = YES; + [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor].active = YES; + + self.positionConstraint = [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor]; + self.positionConstraint.active = YES; +} + +#pragma mark Private Methods + +- (void)layoutContentView { + CGFloat minimumHeight = MIN(self.minimumHeight, self.height); + CGFloat relativeYOffset = self.scrollView.contentOffset.y + self.scrollView.contentInset.top - self.height; + CGFloat relativeHeight = -relativeYOffset; + + self.positionConstraint.constant = relativeYOffset; + self.heightConstraint.constant = MAX(relativeHeight, minimumHeight); + + [self.contentView layoutSubviews]; + + CGFloat div = self.height - self.minimumHeight; + self.progress = (self.contentView.frame.size.height - self.minimumHeight) / (div? : self.height); +} + +- (void)adjustScrollViewTopInset:(CGFloat)top { + UIEdgeInsets inset = self.scrollView.contentInset; + + //Adjust content offset + CGPoint offset = self.scrollView.contentOffset; + offset.y += inset.top - top; + self.scrollView.contentOffset = offset; + + //Adjust content inset + inset.top = top; + self.scrollView.contentInset = inset; +} + +#pragma mark KVO + +//This is where the magic happens... +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + + if (context == kMXParallaxHeaderKVOContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(contentOffset))]) { + [self layoutContentView]; + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +@end + +@implementation UIScrollView (MXParallaxHeader) + +- (MXParallaxHeader *)parallaxHeader { + MXParallaxHeader *parallaxHeader = objc_getAssociatedObject(self, @selector(parallaxHeader)); + if (!parallaxHeader) { + parallaxHeader = [MXParallaxHeader new]; + [self setParallaxHeader:parallaxHeader]; + } + return parallaxHeader; +} + +- (void)setParallaxHeader:(MXParallaxHeader *)parallaxHeader { + parallaxHeader.scrollView = self; + objc_setAssociatedObject(self, @selector(parallaxHeader), parallaxHeader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/QuickLocation/UIKit/MXParallaxHeader/MXScrollView.h b/QuickLocation/UIKit/MXParallaxHeader/MXScrollView.h new file mode 100644 index 00000000..76ca0b5c --- /dev/null +++ b/QuickLocation/UIKit/MXParallaxHeader/MXScrollView.h @@ -0,0 +1,59 @@ +// MXScrollView.h +// +// Copyright (c) 2019 Maxime Epain +// +// 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 "MXParallaxHeader.h" + +NS_ASSUME_NONNULL_BEGIN + +@class MXScrollView; + +/** + The delegate of a MXScrollView object may adopt the MXScrollViewDelegate protocol to control subview's scrolling effect. + */ +@protocol MXScrollViewDelegate + +@optional +/** + Asks the page if the scrollview should scroll with the subview. + + @param scrollView The scrollview. This is the object sending the message. + @param subView An instance of a sub view. + + @return YES to allow scrollview and subview to scroll together. YES by default. + */ +- (BOOL)scrollView:(MXScrollView *)scrollView shouldScrollWithSubView:(UIScrollView *)subView; + +@end + +/** + The MXScrollView is a UIScrollView subclass with the ability to hook the vertical scroll from its subviews. + */ +@interface MXScrollView : UIScrollView + +/** + Delegate instance that adopt the MXScrollViewDelegate. + */ +@property (nonatomic, weak, nullable) IBOutlet id delegate; + +@end + +NS_ASSUME_NONNULL_END diff --git a/QuickLocation/UIKit/MXParallaxHeader/MXScrollView.m b/QuickLocation/UIKit/MXParallaxHeader/MXScrollView.m new file mode 100644 index 00000000..59a51b5e --- /dev/null +++ b/QuickLocation/UIKit/MXParallaxHeader/MXScrollView.m @@ -0,0 +1,275 @@ +// MXScrollView.m +// +// Copyright (c) 2019 Maxime Epain +// +// 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 "MXScrollView.h" + +@interface MXScrollViewDelegateForwarder : NSObject +@property (nonatomic,weak) id delegate; +@end + +@interface MXScrollView () +@property (nonatomic, strong) MXScrollViewDelegateForwarder *forwarder; +@property (nonatomic, strong) NSMutableArray *observedViews; +@end + +@implementation MXScrollView { + BOOL _isObserving; + BOOL _lock; +} + +static void * const kMXScrollViewKVOContext = (void*)&kMXScrollViewKVOContext; + +@synthesize delegate = _delegate; +@synthesize bounces = _bounces; + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame: frame]; + if (self) { + [self initialize]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)coder { + self = [super initWithCoder:coder]; + if (self) { + [self initialize]; + } + return self; +} + +- (void)initialize { + self.forwarder = [MXScrollViewDelegateForwarder new]; + super.delegate = self.forwarder; + + self.showsVerticalScrollIndicator = NO; + self.directionalLockEnabled = YES; + self.bounces = YES; + + self.panGestureRecognizer.cancelsTouchesInView = NO; + + self.observedViews = [NSMutableArray array]; + + [self addObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset)) + options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld + context:kMXScrollViewKVOContext]; + _isObserving = YES; +} + +#pragma mark Properties + +- (void)setDelegate:(id)delegate { + self.forwarder.delegate = delegate; + // Scroll view delegate caches whether the delegate responds to some of the delegate + // methods, so we need to force it to re-evaluate if the delegate responds to them + super.delegate = nil; + super.delegate = self.forwarder; +} + +- (id)delegate { + return self.forwarder.delegate; +} + +#pragma mark + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { + + if (otherGestureRecognizer.view == self) { + return NO; + } + + // Ignore other gesture than pan + if (![gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) { + return NO; + } + + // Lock horizontal pan gesture. + CGPoint velocity = [(UIPanGestureRecognizer*)gestureRecognizer velocityInView:self]; + if (fabs(velocity.x) > fabs(velocity.y)) { + return NO; + } + + UIView *otherView = otherGestureRecognizer.view; + // WKWebView on he MXScrollView + if ([otherView isKindOfClass:NSClassFromString(@"WKContentView")]) { + otherView = otherView.superview; + } + // Consider scroll view pan only + if (![otherView isKindOfClass:[UIScrollView class]]) { + return NO; + } + + UIScrollView *scrollView = (id)otherView; + + // Tricky case: UITableViewWrapperView + if ([scrollView.superview isKindOfClass:[UITableView class]]) { + return NO; + } + //tableview on the MXScrollView + if ([scrollView.superview isKindOfClass:NSClassFromString(@"UITableViewCellContentView")]) { + return NO; + } + + BOOL shouldScroll = YES; + if ([self.delegate respondsToSelector:@selector(scrollView:shouldScrollWithSubView:)]) { + shouldScroll = [self.delegate scrollView:self shouldScrollWithSubView:scrollView];; + } + + if (shouldScroll) { + [self addObservedView:scrollView]; + } + + return shouldScroll; +} + +#pragma mark KVO + +- (void)addObserverToView:(UIScrollView *)scrollView { + _lock = (scrollView.contentOffset.y > -scrollView.contentInset.top); + + [scrollView addObserver:self + forKeyPath:NSStringFromSelector(@selector(contentOffset)) + options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew + context:kMXScrollViewKVOContext]; +} + +- (void)removeObserverFromView:(UIScrollView *)scrollView { + @try { + [scrollView removeObserver:self + forKeyPath:NSStringFromSelector(@selector(contentOffset)) + context:kMXScrollViewKVOContext]; + } + @catch (NSException *exception) {} +} + +//This is where the magic happens... +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + + if (context == kMXScrollViewKVOContext && [keyPath isEqualToString:NSStringFromSelector(@selector(contentOffset))]) { + + CGPoint new = [[change objectForKey:NSKeyValueChangeNewKey] CGPointValue]; + CGPoint old = [[change objectForKey:NSKeyValueChangeOldKey] CGPointValue]; + CGFloat diff = old.y - new.y; + + if (diff == 0.0 || !_isObserving) return; + + if (object == self) { + + //Adjust self scroll offset when scroll down + if (diff > 0 && _lock) { + [self scrollView:self setContentOffset:old]; + + } else if (self.contentOffset.y < -self.contentInset.top && !self.bounces) { + [self scrollView:self setContentOffset:CGPointMake(self.contentOffset.x, -self.contentInset.top)]; + } else if (self.contentOffset.y > -self.parallaxHeader.minimumHeight) { + [self scrollView:self setContentOffset:CGPointMake(self.contentOffset.x, -self.parallaxHeader.minimumHeight)]; + } + + } else { + //Adjust the observed scrollview's content offset + UIScrollView *scrollView = object; + _lock = (scrollView.contentOffset.y > -scrollView.contentInset.top); + + //Manage scroll up + if (self.contentOffset.y < -self.parallaxHeader.minimumHeight && _lock && diff < 0) { + [self scrollView:scrollView setContentOffset:old]; + } + //Disable bouncing when scroll down + if (!_lock && ((self.contentOffset.y > -self.contentInset.top) || self.bounces)) { + [self scrollView:scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, -scrollView.contentInset.top)]; + } + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +#pragma mark Scrolling views handlers + +- (void)addObservedView:(UIScrollView *)scrollView { + if (![self.observedViews containsObject:scrollView]) { + [self.observedViews addObject:scrollView]; + [self addObserverToView:scrollView]; + } +} + +- (void)removeObservedViews { + for (UIScrollView *scrollView in self.observedViews) { + [self removeObserverFromView:scrollView]; + } + [self.observedViews removeAllObjects]; +} + +- (void)scrollView:(UIScrollView *)scrollView setContentOffset:(CGPoint)offset { + _isObserving = NO; + scrollView.contentOffset = offset; + _isObserving = YES; +} + +- (void)dealloc { + [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset)) context:kMXScrollViewKVOContext]; + [self removeObservedViews]; +} + +#pragma mark + +- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { + _lock = NO; + [self removeObservedViews]; +} + +- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { + if (!decelerate) { + _lock = NO; + [self removeObservedViews]; + } +} + +@end + +@implementation MXScrollViewDelegateForwarder + +- (BOOL)respondsToSelector:(SEL)selector { + return [self.delegate respondsToSelector:selector] || [super respondsToSelector:selector]; +} + +- (void)forwardInvocation:(NSInvocation *)invocation { + [invocation invokeWithTarget:self.delegate]; +} + +#pragma mark + +- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { + [(MXScrollView *)scrollView scrollViewDidEndDecelerating:scrollView]; + if ([self.delegate respondsToSelector:_cmd]) { + [self.delegate scrollViewDidEndDecelerating:scrollView]; + } +} + +- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { + [(MXScrollView *)scrollView scrollViewDidEndDragging:scrollView willDecelerate:decelerate]; + if ([self.delegate respondsToSelector:_cmd]) { + [self.delegate scrollViewDidEndDragging:scrollView willDecelerate:decelerate]; + } +} + +@end diff --git a/QuickLocation/UIKit/MXParallaxHeader/MXScrollViewController.h b/QuickLocation/UIKit/MXParallaxHeader/MXScrollViewController.h new file mode 100644 index 00000000..36565cc4 --- /dev/null +++ b/QuickLocation/UIKit/MXParallaxHeader/MXScrollViewController.h @@ -0,0 +1,75 @@ +// MXScrollViewController.h +// +// Copyright (c) 2019 Maxime Epain +// +// 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 "MXScrollView.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + The MXScrollViewController class. + */ +@interface MXScrollViewController : UIViewController + +/** + The scroll view container. + */ +@property (nonatomic, readonly) MXScrollView *scrollView; + +/** + The parallax header view controller to be added to the scroll view. + */ +@property (nonatomic, strong, nullable) UIViewController *headerViewController; + +/** + The child view controller to be added to the scroll view. + */ +@property (nonatomic, strong, nullable) UIViewController *childViewController; + +@end + +/** + UIViewController category to let childViewControllers easily access their parallax header. + */ +@interface UIViewController (MXParallaxHeader) + +/** + The parallax header. + */ +@property (nonatomic, readonly, nullable) MXParallaxHeader *parallaxHeader; + +@end + +/** + The MXParallaxHeaderSegue class creates a segue object to get the parallax header view controller from storyboard. + */ +@interface MXParallaxHeaderSegue : UIStoryboardSegue + +@end + +/** + The MXScrollViewControllerSegue class creates a segue object to get the child view controller from storyboard. + */ +@interface MXScrollViewControllerSegue : UIStoryboardSegue + +@end + +NS_ASSUME_NONNULL_END diff --git a/QuickLocation/UIKit/MXParallaxHeader/MXScrollViewController.m b/QuickLocation/UIKit/MXParallaxHeader/MXScrollViewController.m new file mode 100644 index 00000000..99f369e1 --- /dev/null +++ b/QuickLocation/UIKit/MXParallaxHeader/MXScrollViewController.m @@ -0,0 +1,240 @@ +// MXScrollViewController.m +// +// Copyright (c) 2019 Maxime Epain +// +// 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 +#import "MXScrollViewController.h" + +@interface MXScrollViewController () +@property (nonatomic, weak) IBOutlet UIView *headerView; +@property (nonatomic) IBInspectable CGFloat headerHeight; +@property (nonatomic) IBInspectable CGFloat headerMinimumHeight; +@property (nonatomic, weak) NSLayoutConstraint *childHeightConstraint; +@end + +@implementation MXScrollViewController + +static void * const kMXScrollViewControllerKVOContext = (void*)&kMXScrollViewControllerKVOContext; + +@synthesize scrollView = _scrollView; +@dynamic headerHeight; +@dynamic headerMinimumHeight; + +- (void)viewDidLoad { + [super viewDidLoad]; + + self.scrollView.translatesAutoresizingMaskIntoConstraints = NO; + + [self.view addSubview:self.scrollView]; + [self.scrollView.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES; + [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES; + [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES; + [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES; + + self.scrollView.parallaxHeader.view = self.headerView; + self.scrollView.parallaxHeader.height = self.headerHeight; + self.scrollView.parallaxHeader.minimumHeight = self.headerMinimumHeight; + + //Hack to perform segues on load + @try { + NSArray *templates = [self valueForKey:@"storyboardSegueTemplates"]; + for (id template in templates) { + NSString *segueClasseName = [template valueForKey:@"_segueClassName"]; + if ([segueClasseName isEqualToString:NSStringFromClass(MXScrollViewControllerSegue.class)] || + [segueClasseName isEqualToString:NSStringFromClass(MXParallaxHeaderSegue.class)]) { + NSString *identifier = [template valueForKey:@"identifier"]; + [self performSegueWithIdentifier:identifier sender:self]; + } + } + } + @catch(NSException *exception) { + NSLog(@"%@", exception); + } +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + + if (@available(iOS 11.0, *)) return; + + if (self.automaticallyAdjustsScrollViewInsets) { + self.headerMinimumHeight = self.topLayoutGuide.length; + } +} + +- (void)viewSafeAreaInsetsDidChange { + [super viewSafeAreaInsetsDidChange]; + + if (self.scrollView.contentInsetAdjustmentBehavior != UIScrollViewContentInsetAdjustmentNever) { + self.headerMinimumHeight = self.view.safeAreaInsets.top; + + UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero; + safeAreaInsets.bottom = self.view.safeAreaInsets.bottom; + self.childViewController.additionalSafeAreaInsets = safeAreaInsets; + } +} + +#pragma mark Properties + +- (MXScrollView *)scrollView { + if (!_scrollView) { + _scrollView = [[MXScrollView alloc] init]; + + [_scrollView.parallaxHeader addObserver:self + forKeyPath:NSStringFromSelector(@selector(minimumHeight)) + options:NSKeyValueObservingOptionNew + context:kMXScrollViewControllerKVOContext]; + } + return _scrollView; +} + +- (void)setHeaderViewController:(UIViewController *)headerViewController { + if (_headerViewController.parentViewController == self) { + [_headerViewController willMoveToParentViewController:nil]; + [_headerViewController.view removeFromSuperview]; + [_headerViewController removeFromParentViewController]; + [_headerViewController didMoveToParentViewController:nil]; + } + + if (headerViewController) { + [headerViewController willMoveToParentViewController:self]; + [self addChildViewController:headerViewController]; + + //Set parallaxHeader view + objc_setAssociatedObject(headerViewController, @selector(parallaxHeader), self.scrollView.parallaxHeader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + self.scrollView.parallaxHeader.view = headerViewController.view; + [headerViewController didMoveToParentViewController:self]; + } + _headerViewController = headerViewController; +} + +- (void)setChildViewController:(UIViewController *)childViewController { + if (_childViewController.parentViewController == self) { + [_childViewController willMoveToParentViewController:nil]; + [_childViewController.view removeFromSuperview]; + [_childViewController removeFromParentViewController]; + [_childViewController didMoveToParentViewController:nil]; + } + + if (childViewController) { + [childViewController willMoveToParentViewController:self]; + [self addChildViewController:childViewController]; + + // Set UIViewController's parallaxHeader property + objc_setAssociatedObject(childViewController, @selector(parallaxHeader), self.scrollView.parallaxHeader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + [self.scrollView addSubview:childViewController.view]; + + // Set child's constraints + childViewController.view.translatesAutoresizingMaskIntoConstraints = NO; + + [childViewController.view.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor].active = YES; + [childViewController.view.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor].active = YES; + [childViewController.view.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor].active = YES; + + [childViewController.view.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor].active = YES; + [childViewController.view.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor].active = YES; + + self.childHeightConstraint = [childViewController.view.heightAnchor constraintEqualToAnchor:self.scrollView.heightAnchor constant:-self.headerMinimumHeight]; + self.childHeightConstraint.active = YES; + + [childViewController didMoveToParentViewController:self]; + + } + _childViewController = childViewController; +} + +- (void)setHeaderHeight:(CGFloat)headerHeight { + self.scrollView.parallaxHeader.height = headerHeight; +} + +- (CGFloat)headerHeight { + return self.scrollView.parallaxHeader.height; +} + +- (void)setHeaderMinimumHeight:(CGFloat)headerMinimumHeight { + self.childHeightConstraint.constant = -headerMinimumHeight; + self.scrollView.parallaxHeader.minimumHeight = headerMinimumHeight; +} + +- (CGFloat)headerMinimumHeight { + return self.scrollView.parallaxHeader.minimumHeight; +} + +#pragma mark KVO + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (context == kMXScrollViewControllerKVOContext) { + + if (self.childViewController && [keyPath isEqualToString:NSStringFromSelector(@selector(minimumHeight))]) { + self.childHeightConstraint.constant = -self.scrollView.parallaxHeader.minimumHeight; + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +- (void)dealloc { + [self.scrollView.parallaxHeader removeObserver:self forKeyPath:NSStringFromSelector(@selector(minimumHeight))]; +} + +@end + +#pragma mark UIViewController category + +@implementation UIViewController (MXParallaxHeader) + +- (MXParallaxHeader *)parallaxHeader { + MXParallaxHeader *parallaxHeader = objc_getAssociatedObject(self, @selector(parallaxHeader)); + if (!parallaxHeader && self.parentViewController) { + return self.parentViewController.parallaxHeader; + } + return parallaxHeader; +} + +@end + +#pragma mark MXParallaxHeaderSegue class + +@implementation MXParallaxHeaderSegue + +- (void)perform { + if ([self.sourceViewController isKindOfClass:[MXScrollViewController class]]) { + MXScrollViewController *svc = self.sourceViewController; + svc.headerViewController = self.destinationViewController; + } +} + +@end + +#pragma mark MXScrollViewControllerSegue class + +@implementation MXScrollViewControllerSegue + +- (void)perform { + if ([self.sourceViewController isKindOfClass:[MXScrollViewController class]]) { + MXScrollViewController *svc = self.sourceViewController; + svc.childViewController = self.destinationViewController; + } +} + +@end diff --git a/QuickLocation/UIKit/PageView/Helper.swift b/QuickLocation/UIKit/PageView/Helper.swift new file mode 100644 index 00000000..9341d015 --- /dev/null +++ b/QuickLocation/UIKit/PageView/Helper.swift @@ -0,0 +1,101 @@ +// +// Helper.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 struct DNSExtension { + internal let type: ExtendedType + internal init(_ type: ExtendedType) { + self.type = type + } +} + + +public protocol DNSExtended { + +} + +extension DNSExtended { + public var dns: DNSExtension { + get { DNSExtension(self) } + } + public static var dns: DNSExtension.Type { + get { DNSExtension.self } + } +} + +extension UIColor: DNSExtended {} +public extension DNSExtension where ExtendedType: UIColor { + + @available(iOS 13.0, *) + static func dynamic(_ light: UIColor, dark: UIColor) -> UIColor { + return UIColor { traitCollection -> UIColor in + if traitCollection.userInterfaceStyle == .light { + return light + } else { + return dark + } + } + } +} + +extension UIView: DNSExtended {} +public extension DNSExtension where ExtendedType: UIView { + static func isRightToLeftLayoutDirection(_ view: UIView? = nil) -> Bool { + let context: UIView = view ?? UIView.appearance() + if UIView.userInterfaceLayoutDirection(for: context.semanticContentAttribute) == .rightToLeft { + return true + } else { + return false + } + } +} + + + + +typealias ColorRGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) + +extension UIColor { + + convenience init(_ rgba: ColorRGBA) { + self.init(red: rgba.red / 255.0, green: rgba.green / 255.0, blue: rgba.blue / 255.0, alpha: rgba.alpha) + } + + + func getRGBA() -> ColorRGBA { + var red: CGFloat = 0 + var green: CGFloat = 0 + var blue: CGFloat = 0 + var alpha: CGFloat = 0 + getRed(&red, green: &green, blue: &blue, alpha: &alpha) + return (red * 255, green * 255, blue * 255, alpha) + } +} + + diff --git a/QuickLocation/UIKit/PageView/PageCollectionViewFlowLayout.swift b/QuickLocation/UIKit/PageView/PageCollectionViewFlowLayout.swift new file mode 100644 index 00000000..e4f157d1 --- /dev/null +++ b/QuickLocation/UIKit/PageView/PageCollectionViewFlowLayout.swift @@ -0,0 +1,42 @@ +// +// PageCollectionViewFlowLayout.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 + +/// 通过设置 offset 的值,达到初始化的 pageView 默认显示某一页的效果,默认显示第一页 +public class PageCollectionViewFlowLayout: UICollectionViewFlowLayout { + var offset: CGFloat? + + public override func prepare() { + super.prepare() + guard let offset = offset else { return } + collectionView?.contentOffset = CGPoint(x: offset, y: 0) + } + + public override var flipsHorizontallyInOppositeLayoutDirection: Bool { + return true + } +} diff --git a/QuickLocation/UIKit/PageView/PageContentView.swift b/QuickLocation/UIKit/PageView/PageContentView.swift new file mode 100644 index 00000000..1115757c --- /dev/null +++ b/QuickLocation/UIKit/PageView/PageContentView.swift @@ -0,0 +1,253 @@ +// +// PageContentView.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 protocol PageContentViewDelegate: AnyObject { + func contentView(_ contentView: PageContentView, didEndScrollAt index: Int) + func contentView(_ contentView: PageContentView, scrollingWith sourceIndex: Int, targetIndex: Int, progress: CGFloat) +} + + +private let CellID = "CellID" +public class PageContentView: UIView { + + public weak var delegate: PageContentViewDelegate? + + public weak var container: PageViewContainer? + + public weak var eventHandler: PageEventHandleable? + + private (set) public var style: PageStyle = PageStyle() { + didSet { + collectionView.semanticContentAttribute = style.isRTL ? .forceRightToLeft : .forceLeftToRight + } + } + + private (set) public var childViewControllers : [UIViewController] = [UIViewController]() + + /// 初始化后,默认显示的页数 + private (set) public var currentIndex: Int { + didSet { + guard delegate == nil else { return } + container?.updateCurrentIndex(currentIndex) + } + } + + private var startOffsetX: CGFloat = 0 + + private var isForbidDelegate: Bool = false + + private (set) public lazy var collectionView: UICollectionView = { + let layout = PageCollectionViewFlowLayout() + layout.minimumLineSpacing = 0 + layout.minimumInteritemSpacing = 0 + layout.scrollDirection = .horizontal + + let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) + collectionView.showsHorizontalScrollIndicator = false + collectionView.isPagingEnabled = true + collectionView.scrollsToTop = false + collectionView.dataSource = self + collectionView.delegate = self + collectionView.bounces = false + if #available(iOS 10, *) { + collectionView.isPrefetchingEnabled = false + } + collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CellID) + return collectionView + }() + + + public init(frame: CGRect, style: PageStyle, childViewControllers: [UIViewController], currentIndex: Int = 0) { + assert(currentIndex >= 0 && currentIndex < childViewControllers.count, + "currentIndex < 0 or currentIndex >= childViewControllers.count") + self.currentIndex = currentIndex + super.init(frame: frame) + addSubview(collectionView) + configure(childViewControllers: childViewControllers, style: style, currentIndex: currentIndex) + } + + required public init?(coder aDecoder: NSCoder) { + self.currentIndex = 0 + super.init(coder: aDecoder) + addSubview(collectionView) + } + + public override func layoutSubviews() { + super.layoutSubviews() + collectionView.frame = CGRect(origin: CGPoint.zero, size: frame.size) + let layout = collectionView.collectionViewLayout as! PageCollectionViewFlowLayout + layout.itemSize = frame.size + layout.offset = CGFloat(currentIndex) * frame.size.width + layout.invalidateLayout() + } +} + + +extension PageContentView { + internal func configure(childViewControllers: [UIViewController]? = nil, style: PageStyle? = nil, currentIndex: Int? = nil) { + if let childViewControllers = childViewControllers { + self.childViewControllers = childViewControllers + } + if let style = style { + self.style = style + } + if let currentIndex = currentIndex { + collectionView.collectionViewLayout.invalidateLayout() + self.currentIndex = currentIndex + } + configureSubViews() + collectionView.reloadData() + setNeedsLayout() + } + + private func configureSubViews() { + collectionView.backgroundColor = style.contentViewBackgroundColor + collectionView.isScrollEnabled = style.isContentScrollEnabled + } +} + + +extension PageContentView: UICollectionViewDataSource { + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return childViewControllers.count + } + + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellID, for: indexPath) + + for subview in cell.contentView.subviews { + subview.removeFromSuperview() + } + let childViewController = childViewControllers[indexPath.item] + + eventHandler = childViewController as? PageEventHandleable + childViewController.view.frame = CGRect(origin: CGPoint.zero, size: cell.contentView.frame.size) + + cell.contentView.addSubview(childViewController.view) + + return cell + } +} + + +extension PageContentView: UICollectionViewDelegate { + + + public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + isForbidDelegate = false + startOffsetX = scrollView.contentOffset.x + + } + + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + updateUI(scrollView) + } + + + public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { + if !decelerate { + collectionViewDidEndScroll(scrollView) + } + } + + public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { + collectionViewDidEndScroll(scrollView) + } + + + private func collectionViewDidEndScroll(_ scrollView: UIScrollView) { + + let index = Int(round(scrollView.contentOffset.x / scrollView.frame.width)) + + delegate?.contentView(self, didEndScrollAt: index) + + if index != currentIndex { + let childViewController = childViewControllers[currentIndex] + (childViewController as? PageEventHandleable)?.contentViewDidDisappear() + } + + currentIndex = index + + eventHandler = childViewControllers[currentIndex] as? PageEventHandleable + + eventHandler?.contentViewDidEndScroll() + + } + + + + private func updateUI(_ scrollView: UIScrollView) { + if isForbidDelegate { + return + } + + var progress: CGFloat = 0 + var targetIndex = 0 + var sourceIndex = 0 + + + progress = scrollView.contentOffset.x.truncatingRemainder(dividingBy: scrollView.frame.width) / scrollView.frame.width + if progress == 0 || progress.isNaN { + return + } + let index = Int(scrollView.contentOffset.x / scrollView.frame.width) + if collectionView.contentOffset.x > startOffsetX { // 左滑动 + sourceIndex = index + targetIndex = index + 1 + } else { + sourceIndex = index + 1 + targetIndex = index + progress = 1 - progress + } + guard targetIndex < childViewControllers.count && targetIndex >= 0 else { return } + + + if progress > 0.998 { + progress = 1 + } + + delegate?.contentView(self, scrollingWith: sourceIndex, targetIndex: targetIndex, progress: progress) + } +} + + +extension PageContentView: PageTitleViewDelegate { + public func titleView(_ titleView: PageTitleView, didSelectAt index: Int) { + isForbidDelegate = true + + guard currentIndex < childViewControllers.count else { return } + + currentIndex = index + + let indexPath = IndexPath(item: index, section: 0) + + collectionView.scrollToItem(at: indexPath, at: .left, animated: false) + } +} + + diff --git a/QuickLocation/UIKit/PageView/PageStyle.swift b/QuickLocation/UIKit/PageView/PageStyle.swift new file mode 100644 index 00000000..e5efd082 --- /dev/null +++ b/QuickLocation/UIKit/PageView/PageStyle.swift @@ -0,0 +1,102 @@ +// +// PageStyle.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 PageStyle { + + public enum UserInterfaceLayoutDirection { + case unspecified + case forceLeftToRight + case forceRightToLeft + } + + public enum BottomLineStyle { + case auto + case average + case custom + } + + /// titleView + public var titleViewHeight: CGFloat = 44 + public var titleColor: UIColor = UIColor.black + public var titleSelectedColor: UIColor = UIColor.blue + public var titleFont: UIFont = UIFont.systemFont(ofSize: 15) + public var titleSelectedFont: UIFont? + public var titleViewBackgroundColor: UIColor = UIColor.white + public var titleViewSelectedColor: UIColor = UIColor.clear + public var titleMargin: CGFloat = 30 + public var titleInset: CGFloat = 0 + + + /// titleView 滑动 + public var isTitleViewScrollEnabled: Bool = false + + /// title 下划线 + public var isShowBottomLine: Bool = false + public var bottomLineColor: UIColor = UIColor.blue + public var bottomLineHeight: CGFloat = 2 + public var bottomLineWidth: CGFloat = 0 + public var bottomLineRadius: CGFloat = 1 + public var bottomLineSytle: BottomLineStyle = .auto + + + /// title 缩放 + public var isTitleScaleEnabled: Bool = false + public var titleMaximumScaleFactor: CGFloat = 1.2 + + /// title 遮罩 + public var isShowCoverView: Bool = false + public var coverViewBackgroundColor: UIColor = UIColor.black + public var coverViewAlpha: CGFloat = 0.4 + public var coverMargin: CGFloat = 8 + public var coverViewHeight: CGFloat = 25 + public var coverViewRadius: CGFloat = 12 + + + /// contentView + public var isContentScrollEnabled : Bool = true + public var contentViewBackgroundColor = UIColor.white + + /// 设置布局方向,默认跟随系统 + public var userInterfaceLayoutDirection: UserInterfaceLayoutDirection = .unspecified + + /// 获取当前 PageView 实际的布局方向 + public var isRTL: Bool { + get { + switch userInterfaceLayoutDirection { + case .unspecified: + return UIView.dns.isRightToLeftLayoutDirection() + case .forceLeftToRight: + return false + case .forceRightToLeft: + return true + } + } + } + + public init() {} +} diff --git a/QuickLocation/UIKit/PageView/PageTitleView.swift b/QuickLocation/UIKit/PageView/PageTitleView.swift new file mode 100644 index 00000000..955b95a9 --- /dev/null +++ b/QuickLocation/UIKit/PageView/PageTitleView.swift @@ -0,0 +1,582 @@ +// +// PageTitleView.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 protocol PageTitleViewDelegate: AnyObject { + + /// DNSPageView 的事件回调处理者 + var eventHandler: PageEventHandleable? { get } + + func titleView(_ titleView: PageTitleView, didSelectAt index: Int) +} + +/// DNSPageView 的事件回调,如果有需要,请让对应的 childViewController 遵守这个协议 +public protocol PageEventHandleable: AnyObject { + + /// 重复点击 pageTitleView 后调用 + func titleViewDidSelectSameTitle() + + /// pageContentView 的上一页消失的时候,上一页对应的 controller 调用 + func contentViewDidDisappear() + + /// pageContentView 滚动停止的时候,当前页对应的 controller 调用 + func contentViewDidEndScroll() + +} + +extension PageEventHandleable { + func titleViewDidSelectSameTitle() {} + + func contentViewDidDisappear() {} + + func contentViewDidEndScroll() {} +} + +public typealias TitleClickHandler = (PageTitleView, Int) -> () + +public class PageTitleView: UIView { + + public weak var delegate: PageTitleViewDelegate? + + public weak var container: PageViewContainer? + + /// 点击标题时调用 + public var clickHandler: TitleClickHandler? + + private (set) public var currentIndex: Int { + didSet { + container?.updateCurrentIndex(currentIndex) + } + } + + private (set) public lazy var titleLabels: [UILabel] = [UILabel]() + + private (set) public var style: PageStyle = PageStyle() + + private (set) public var titles: [String] = [String]() + + + private lazy var normalRGBA: ColorRGBA = style.titleColor.getRGBA() + private lazy var selectRGBA: ColorRGBA = style.titleSelectedColor.getRGBA() + private lazy var deltaRGBA: ColorRGBA = { + let deltaR = selectRGBA.red - normalRGBA.red + let deltaG = selectRGBA.green - normalRGBA.green + let deltaB = selectRGBA.blue - normalRGBA.blue + let deltaA = selectRGBA.alpha - normalRGBA.alpha + return (deltaR, deltaG, deltaB, deltaA) + }() + + private lazy var scrollView: UIScrollView = { + let scrollView = UIScrollView() + scrollView.showsHorizontalScrollIndicator = false + scrollView.scrollsToTop = false + return scrollView + }() + + private lazy var bottomLine: UIView = UIView() + + private (set) public lazy var coverView: UIView = UIView() + + public init(frame: CGRect, style: PageStyle, titles: [String], currentIndex: Int = 0) { + assert(currentIndex >= 0 && currentIndex < titles.count, + "currentIndex < 0 or currentIndex >= titles.count") + self.currentIndex = style.isRTL ? titles.count - 1 : 0 + super.init(frame: frame) + addSubview(scrollView) + configure(titles: titles, style: style, currentIndex: currentIndex) + } + + required public init?(coder aDecoder: NSCoder) { + self.currentIndex = style.isRTL ? titles.count - 1 : 0 + super.init(coder: aDecoder) + addSubview(scrollView) + } + + + public override func layoutSubviews() { + super.layoutSubviews() + scrollView.frame = CGRect(origin: .zero, size: frame.size) + guard titles.count > 0 else { return } + layoutLabels() + layoutBottomLine() + layoutCoverView() + } + + public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + updateColors() + } + + private func updateColors() { + normalRGBA = style.titleColor.getRGBA() + selectRGBA = style.titleSelectedColor.getRGBA() + let deltaR = selectRGBA.red - normalRGBA.red + let deltaG = selectRGBA.green - normalRGBA.green + let deltaB = selectRGBA.blue - normalRGBA.blue + let deltaA = selectRGBA.alpha - normalRGBA.alpha + deltaRGBA = (deltaR, deltaG, deltaB, deltaA) + + } + + /// 通过代码实现点了某个位置的 titleView + /// + /// - Parameter index: 需要点击的 titleView 的索引 + public func selectedTitle(at index: Int, animated: Bool = true) { + if index > titles.count || index < 0 { + print("PageTitleView -- selectedTitle: 数组越界了, index 的值超出有效范围"); + return; + } + + clickHandler?(self, index) + + if index == currentIndex { + delegate?.eventHandler?.titleViewDidSelectSameTitle() + return + } + + let sourceLabel = titleLabels[currentIndex] + let targetLabel = titleLabels[index] + + sourceLabel.textColor = style.titleColor + targetLabel.textColor = style.titleSelectedColor + + delegate?.eventHandler?.contentViewDidDisappear() + + currentIndex = index + + delegate?.titleView(self, didSelectAt: currentIndex) + + adjustLabelPosition(targetLabel, animated: animated) + + if let font = style.titleSelectedFont { + sourceLabel.font = style.titleFont + targetLabel.font = font + } + + if style.isTitleScaleEnabled { + if animated { + UIView.animate(withDuration: 0.25, animations: { + sourceLabel.transform = CGAffineTransform.identity + targetLabel.transform = CGAffineTransform(scaleX: self.style.titleMaximumScaleFactor, y: self.style.titleMaximumScaleFactor) + }) + } else { + sourceLabel.transform = CGAffineTransform.identity + targetLabel.transform = CGAffineTransform(scaleX: self.style.titleMaximumScaleFactor, y: self.style.titleMaximumScaleFactor) + } + } + + if style.isShowBottomLine { + let titleInset = style.isTitleViewScrollEnabled ? style.titleInset : 0 + if animated { + UIView.animate(withDuration: 0.25, animations: { + self.bottomLine.frame.size.width = self.style.bottomLineWidth > 0 ? + self.style.bottomLineWidth : targetLabel.frame.width - titleInset + self.bottomLine.center.x = targetLabel.center.x + }) + } else { + self.bottomLine.frame.size.width = self.style.bottomLineWidth > 0 ? + self.style.bottomLineWidth : targetLabel.frame.width - titleInset + self.bottomLine.center.x = targetLabel.center.x + } + } + + if style.isShowCoverView { + if animated { + UIView.animate(withDuration: 0.25, animations: { + self.coverView.frame.size.width = self.style.isTitleViewScrollEnabled ? + (targetLabel.frame.width + self.style.coverMargin * 2) : targetLabel.frame.width + self.coverView.center.x = targetLabel.center.x + }) + } else { + self.coverView.frame.size.width = self.style.isTitleViewScrollEnabled ? + (targetLabel.frame.width + self.style.coverMargin * 2) : targetLabel.frame.width + self.coverView.center.x = targetLabel.center.x + } + + } + + sourceLabel.backgroundColor = UIColor.clear + targetLabel.backgroundColor = style.titleViewSelectedColor + } + + public func updateTitle(_ title: String, at index: Int) { + if index > titles.count || index < 0 { + print("PageTitleView -- updateTitle(_:at:): 数组越界了, index 的值超出有效范围"); + return; + } + titles[index] = title + titleLabels[index].text = title + setNeedsLayout() + } + +} + + +// MARK: - 构建 UI +extension PageTitleView { + internal func configure(titles: [String]? = nil, style: PageStyle? = nil, currentIndex: Int? = nil) { + if let titles = titles { + self.titles = titles + } + if let style = style { + self.style = style + updateColors() + } + if let currentIndex = currentIndex { + self.currentIndex = currentIndex + } + configureSubViews() + setNeedsLayout() + } + + + private func configureSubViews() { + scrollView.backgroundColor = style.titleViewBackgroundColor + guard titles.count > 0 else { return } + configureLabels() + configureBottomLine() + configureCoverView() + } + + + private func configureLabels() { + if titles.count == titleLabels.count { + for (i, title) in titles.enumerated() { + configureLabel(titleLabels[i], i, title) + } + } else { + titleLabels.forEach { $0.removeFromSuperview() } + titleLabels = [] + for (i, title) in titles.enumerated() { + let label = UILabel() + let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapedTitleLabel(_:))) + label.addGestureRecognizer(tapGes) + label.isUserInteractionEnabled = true + configureLabel(label, i, title) + scrollView.addSubview(label) + titleLabels.append(label) + } + } + } + + private func configureLabel(_ label: UILabel, _ i: Int, _ title: String) { + label.tag = i + label.text = title + label.textColor = i == currentIndex ? style.titleSelectedColor : style.titleColor + label.backgroundColor = i == currentIndex ? style.titleViewSelectedColor : UIColor.clear; + label.textAlignment = .center + label.font = style.titleFont + } + + private func configureBottomLine() { + guard style.isShowBottomLine else { + bottomLine.removeFromSuperview() + return + } + bottomLine.backgroundColor = style.bottomLineColor + bottomLine.layer.cornerRadius = style.bottomLineRadius + scrollView.addSubview(bottomLine) + } + + private func configureCoverView() { + guard style.isShowCoverView else { + coverView.removeFromSuperview() + return + } + coverView.backgroundColor = style.coverViewBackgroundColor + coverView.alpha = style.coverViewAlpha + coverView.layer.cornerRadius = style.coverViewRadius + coverView.layer.masksToBounds = true + scrollView.insertSubview(coverView, at: 0) + } +} + + +// MARK: - Layout +extension PageTitleView { + private func layoutLabels() { + var x: CGFloat = 0 + let y: CGFloat = 0 + var width: CGFloat = 0 + let height = frame.height + let count = titleLabels.count + let averageWidth: CGFloat = frame.width / CGFloat(count) + if style.isRTL { + if style.isTitleViewScrollEnabled { + // 根据总长度是否超过 frame.width,分两种情况布局 + var outOfBounds = false + var preTitleLabelMaxX: CGFloat = 0 + // 如果总长度超过 frame.width,倒序布局 + for (i, titleLabel) in titleLabels.reversed().enumerated() { + width = ((titleLabel.text ?? "") as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), + options: .usesLineFragmentOrigin, + attributes: [NSAttributedString.Key.font : style.titleFont], + context: nil).width + style.titleInset + + x = i == 0 ? style.titleMargin * 0.5 : (preTitleLabelMaxX + style.titleMargin) + preTitleLabelMaxX = x + width + titleLabel.transform = CGAffineTransform.identity + titleLabel.frame = CGRect(x: x, y: y, width: width, height: height) + if x + width > frame.width { + outOfBounds = true + } + } + // 如果总长度不超过 frame.width,顺序布局,但需要从右到左 + if !outOfBounds { + for (i, titleLabel) in titleLabels.enumerated() { + width = (titles[i] as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), + options: .usesLineFragmentOrigin, + attributes: [NSAttributedString.Key.font : style.titleFont], + context: nil).width + style.titleInset + if i == 0 { + x = frame.width - width - style.titleMargin + } else { + x = titleLabels[i - 1].frame.origin.x - width - style.titleMargin + } + titleLabel.transform = CGAffineTransform.identity + titleLabel.frame = CGRect(x: x, y: y, width: width, height: height) + } + } + } else { + for (i, titleLabel) in titleLabels.enumerated() { + width = averageWidth + x = frame.width - width * CGFloat(i + 1) + titleLabel.transform = CGAffineTransform.identity + titleLabel.frame = CGRect(x: x, y: y, width: width, height: height) + } + } + } else { + for (i, titleLabel) in titleLabels.enumerated() { + if style.isTitleViewScrollEnabled { + width = (titles[i] as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), + options: .usesLineFragmentOrigin, + attributes: [NSAttributedString.Key.font : style.titleFont], + context: nil).width + style.titleInset + x = i == 0 ? style.titleMargin * 0.5 : (titleLabels[i - 1].frame.maxX + style.titleMargin) + } else { + width = averageWidth + x = width * CGFloat(i) + } + titleLabel.transform = CGAffineTransform.identity + titleLabel.frame = CGRect(x: x, y: y, width: width, height: height) + } + } + + if let font = style.titleSelectedFont { + titleLabels[currentIndex].font = font + } + if style.isTitleScaleEnabled { + titleLabels[currentIndex].transform = CGAffineTransform(scaleX: style.titleMaximumScaleFactor, y: style.titleMaximumScaleFactor) + } + if style.isTitleViewScrollEnabled { + guard let titleLabel = style.isRTL ? titleLabels.first : titleLabels.last else { return } + scrollView.contentSize.width = titleLabel.frame.maxX + style.titleMargin * 0.5 + } + + adjustLabelPosition(titleLabels[currentIndex], animated: false) + fixUI(titleLabels[currentIndex], animated: false) + } + + private func layoutCoverView() { + guard currentIndex < titleLabels.count else { return } + let label = titleLabels[currentIndex] + var width = label.frame.width + let height = style.coverViewHeight + if style.isTitleViewScrollEnabled { + width += 2 * style.coverMargin + } + coverView.frame.size = CGSize(width: width, height: height) + coverView.center = label.center + } + + private func layoutBottomLine() { + guard currentIndex < titleLabels.count else { return } + let label = titleLabels[currentIndex] + + let titleInset = style.isTitleViewScrollEnabled ? style.titleInset : 0 + + var lineWidth:CGFloat = 0 + switch style.bottomLineSytle { + case .auto: + lineWidth = label.frame.width + case .average: + lineWidth = label.frame.width - titleInset + case .custom: + lineWidth = style.bottomLineWidth + } + bottomLine.frame.size.width = lineWidth + bottomLine.frame.size.height = style.bottomLineHeight + bottomLine.center.x = label.center.x + bottomLine.frame.origin.y = frame.height - bottomLine.frame.height + } +} + +// MARK: - 监听 label 的点击 +extension PageTitleView { + @objc private func tapedTitleLabel(_ tapGes : UITapGestureRecognizer) { + guard let index = tapGes.view?.tag else { return } + selectedTitle(at: index) + } + + + private func adjustLabelPosition(_ targetLabel : UILabel, animated: Bool) { + guard style.isTitleViewScrollEnabled, + scrollView.contentSize.width > scrollView.frame.width + else { return } + + var offsetX = targetLabel.center.x - frame.width * 0.5 + + if offsetX < 0 { + offsetX = 0 + } + if offsetX > scrollView.contentSize.width - scrollView.frame.width { + offsetX = scrollView.contentSize.width - scrollView.frame.width + } + scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: animated) + } +} + + + +extension PageTitleView: PageContentViewDelegate { + public func contentView(_ contentView: PageContentView, didEndScrollAt index: Int) { + + let sourceLabel = titleLabels[currentIndex] + let targetLabel = titleLabels[index] + + if let font = style.titleSelectedFont { + sourceLabel.font = style.titleFont + targetLabel.font = font + } + + sourceLabel.textColor = style.titleColor + sourceLabel.backgroundColor = UIColor.clear + targetLabel.backgroundColor = style.titleViewSelectedColor + + currentIndex = index + + adjustLabelPosition(targetLabel, animated: true) + + fixUI(targetLabel, animated: true) + } + + public func contentView(_ contentView: PageContentView, scrollingWith sourceIndex: Int, targetIndex: Int, progress: CGFloat) { + if sourceIndex >= titleLabels.count || sourceIndex < 0 { + return + } + if targetIndex >= titleLabels.count || targetIndex < 0 { + return + } + let sourceLabel = titleLabels[sourceIndex] + let targetLabel = titleLabels[targetIndex] + sourceLabel.textColor = UIColor((selectRGBA.red - progress * deltaRGBA.red, + selectRGBA.green - progress * deltaRGBA.green, + selectRGBA.blue - progress * deltaRGBA.blue, + selectRGBA.alpha - progress * deltaRGBA.alpha)) + targetLabel.textColor = UIColor((normalRGBA.red + progress * deltaRGBA.red, + normalRGBA.green + progress * deltaRGBA.green, + normalRGBA.blue + progress * deltaRGBA.blue, + normalRGBA.alpha + progress * deltaRGBA.alpha)) + if style.isTitleScaleEnabled { + let deltaScale = style.titleMaximumScaleFactor - 1.0 + sourceLabel.transform = CGAffineTransform(scaleX: style.titleMaximumScaleFactor - progress * deltaScale, + y: style.titleMaximumScaleFactor - progress * deltaScale) + targetLabel.transform = CGAffineTransform(scaleX: 1.0 + progress * deltaScale, + y: 1.0 + progress * deltaScale) + } + + if style.isShowBottomLine { + if style.bottomLineWidth <= 0 { + let titleInset = style.isTitleViewScrollEnabled ? style.titleInset : 0 + let deltaWidth = targetLabel.frame.width - sourceLabel.frame.width + bottomLine.frame.size.width = sourceLabel.frame.width - titleInset + progress * deltaWidth + } + let deltaCenterX = targetLabel.center.x - sourceLabel.center.x + bottomLine.center.x = sourceLabel.center.x + progress * deltaCenterX + } + + if style.isShowCoverView { + let deltaWidth = targetLabel.frame.width - sourceLabel.frame.width + coverView.frame.size.width = style.isTitleViewScrollEnabled ? + (sourceLabel.frame.width + 2 * style.coverMargin + deltaWidth * progress) : + (sourceLabel.frame.width + deltaWidth * progress) + let deltaCenterX = targetLabel.center.x - sourceLabel.center.x + coverView.center.x = sourceLabel.center.x + deltaCenterX * progress + } + } + + private func fixUI(_ targetLabel: UILabel, animated: Bool) { + if animated { + UIView.animate(withDuration: 0.05) { + targetLabel.textColor = self.style.titleSelectedColor + + if self.style.isTitleScaleEnabled { + targetLabel.transform = CGAffineTransform(scaleX: self.style.titleMaximumScaleFactor, y: self.style.titleMaximumScaleFactor) + } + + if self.style.isShowBottomLine { + if self.style.bottomLineWidth <= 0 { + let titleInset = self.style.isTitleViewScrollEnabled ? self.style.titleInset : 0 + self.bottomLine.frame.size.width = targetLabel.frame.width - titleInset + } + self.bottomLine.center.x = targetLabel.center.x + } + + if self.style.isShowCoverView { + self.coverView.frame.size.width = self.style.isTitleViewScrollEnabled ? + (targetLabel.frame.width + 2 * self.style.coverMargin) : + targetLabel.frame.width + self.coverView.center.x = targetLabel.center.x + } + } + } else { + targetLabel.textColor = self.style.titleSelectedColor + + if self.style.isTitleScaleEnabled { + targetLabel.transform = CGAffineTransform(scaleX: self.style.titleMaximumScaleFactor, y: self.style.titleMaximumScaleFactor) + } + + if self.style.isShowBottomLine { + if self.style.bottomLineWidth <= 0 { + let titleInset = self.style.isTitleViewScrollEnabled ? self.style.titleInset : 0 + self.bottomLine.frame.size.width = targetLabel.frame.width - titleInset + } + self.bottomLine.center.x = targetLabel.center.x + } + + if self.style.isShowCoverView { + self.coverView.frame.size.width = self.style.isTitleViewScrollEnabled ? + (targetLabel.frame.width + 2 * self.style.coverMargin) : + targetLabel.frame.width + self.coverView.center.x = targetLabel.center.x + } + } + } + +} + + + diff --git a/QuickLocation/UIKit/PageView/PageView.swift b/QuickLocation/UIKit/PageView/PageView.swift new file mode 100644 index 00000000..80b08bbd --- /dev/null +++ b/QuickLocation/UIKit/PageView/PageView.swift @@ -0,0 +1,112 @@ +// +// PageView.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 + + +/// 通过这个类创建的 pageView,默认 titleView 和 contentView 连在一起,效果类似于网易新闻 +/// 只能用代码创建,不能在 xib 或者 storyboard 里面使用 +public class PageView: UIView { + + private (set) public var style: PageStyle + private (set) public var titles: [String] + private (set) public var childViewControllers: [UIViewController] + private (set) public var currentIndex: Int + public let titleView: PageTitleView + public let contentView: PageContentView + + public init(frame: CGRect, + style: PageStyle, + titles: [String], + childViewControllers: [UIViewController], + currentIndex: Int = 0) { + assert(titles.count == childViewControllers.count, + "titles.count != childViewControllers.count") + assert(currentIndex >= 0 && currentIndex < titles.count, + "currentIndex < 0 or currentIndex >= titles.count") + self.style = style + self.titles = titles + self.childViewControllers = childViewControllers + self.currentIndex = style.isRTL ? self.titles.count - currentIndex - 1 : currentIndex + self.titleView = PageTitleView(frame: CGRect(x: 0, + y: 0, + width: frame.width, + height: style.titleViewHeight), + style: style, + titles: titles, + currentIndex: currentIndex) + self.contentView = PageContentView(frame: CGRect(x: 0, + y: style.titleViewHeight, + width: frame.width, + height: frame.height - style.titleViewHeight), + style: style, + childViewControllers: childViewControllers, + currentIndex: currentIndex) + + super.init(frame: frame) + + addSubview(titleView) + addSubview(contentView) + titleView.container = self + contentView.container = self + titleView.delegate = contentView + contentView.delegate = titleView + } + + public required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + + +extension PageView { + public func configure(titles: [String]? = nil, + childViewControllers: [UIViewController]? = nil, + style: PageStyle? = nil) { + if let titles = titles { + self.titles = titles + } + if let childViewControllers = childViewControllers { + self.childViewControllers = childViewControllers + } + if let style = style { + self.style = style + } + assert(self.titles.count == self.childViewControllers.count, + "titles.count != childViewControllers.count") + assert(currentIndex >= 0 && currentIndex < self.titles.count, + "currentIndex < 0 or currentIndex >= titles.count") + titleView.configure(titles: titles, style: style) + contentView.configure(childViewControllers: childViewControllers, style: style) + } +} + + +extension PageView: PageViewContainer { + public func updateCurrentIndex(_ index: Int) { + currentIndex = index + } +} diff --git a/QuickLocation/UIKit/PageView/PageViewManager.swift b/QuickLocation/UIKit/PageView/PageViewManager.swift new file mode 100644 index 00000000..9864dc66 --- /dev/null +++ b/QuickLocation/UIKit/PageView/PageViewManager.swift @@ -0,0 +1,106 @@ +// +// PageViewManager.swift +// DNSPageView +// +// Created by Daniels on 2018/2/24. +// Copyright © 2018 Daniels. All rights reserved. +// +// 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 protocol PageViewContainer: AnyObject { + + func updateCurrentIndex(_ index: Int) +} + + +/// 通过这个类创建的 pageView,titleView 和 contentView 的 frame 是不确定的,适合于 titleView 和 contentView 分开布局的情况 +/// 需要给 titleView 和 contentView 布局,可以使用 frame 或者 Autolayout +public class PageViewManager { + + private (set) public var style: PageStyle + private (set) public var titles: [String] + private (set) public var childViewControllers: [UIViewController] + private (set) public var currentIndex: Int + public let titleView: PageTitleView + public let contentView: PageContentView + + public init(style: PageStyle, + titles: [String], + childViewControllers: [UIViewController], + currentIndex: Int = 0, + titleView: PageTitleView? = nil, + contentView: PageContentView? = nil) { + + assert(titles.count == childViewControllers.count, + "titles.count != childViewControllers.count") + assert(currentIndex >= 0 && currentIndex < titles.count, + "currentIndex < 0 or currentIndex >= titles.count") + + self.style = style + self.titles = titles + self.childViewControllers = childViewControllers + self.currentIndex = style.isRTL ? titles.count - currentIndex - 1 : currentIndex + + if let titleView = titleView { + self.titleView = titleView + self.titleView.configure(titles: titles, style: style, currentIndex: currentIndex) + } else { + self.titleView = PageTitleView(frame: .zero, style: style, titles: titles, currentIndex: currentIndex) + } + if let contentView = contentView { + self.contentView = contentView + self.contentView.configure(childViewControllers: childViewControllers, style: style, currentIndex: currentIndex) + } else { + self.contentView = PageContentView(frame: .zero, style: style, childViewControllers: childViewControllers, currentIndex: currentIndex) + } + self.titleView.container = self + self.contentView.container = self + self.titleView.delegate = self.contentView + self.contentView.delegate = self.titleView + } + + public func configure(titles: [String]? = nil, + childViewControllers: [UIViewController]? = nil, + style: PageStyle? = nil) { + if let titles = titles { + self.titles = titles + } + if let childViewControllers = childViewControllers { + self.childViewControllers = childViewControllers + } + if let style = style { + self.style = style + } + assert(self.titles.count == self.childViewControllers.count, + "titles.count != childViewControllers.count") + assert(currentIndex >= 0 && currentIndex < self.titles.count, + "currentIndex < 0 or currentIndex >= titles.count") + titleView.configure(titles: titles, style: style) + contentView.configure(childViewControllers: childViewControllers, style: style) + } +} + +extension PageViewManager: PageViewContainer { + public func updateCurrentIndex(_ index: Int) { + currentIndex = index + } +} diff --git a/QuickLocation/UIKit/Pop/DLAlertPopVC.swift b/QuickLocation/UIKit/Pop/DLAlertPopVC.swift new file mode 100644 index 00000000..9ed16146 --- /dev/null +++ b/QuickLocation/UIKit/Pop/DLAlertPopVC.swift @@ -0,0 +1,276 @@ +// +// DLAlertPopVC.swift +// dinoGo +// +// Created by osell on 2022/12/8. +// Copyright © 2022 dino. All rights reserved. +// + +import UIKit +import URLNavigator + +public class DLAlertPopVC: DLCustomPopVC { + + // MARK: - Accessor + public var confirmBlock: (() -> Void)? + public var cancelBlock: (() -> Void)? + public var titleText: String? { + didSet { + titleLabel.text = titleText + } + } + public var contentText: String? { + didSet { + contentLabel.text = contentText + } + } + public var cancelText: String? { + didSet { + cancelBtn.setTitle(cancelText, for: .normal) + } + } + public var confirmText: String? { + didSet { + confirmBtn.setTitle(confirmText, for: .normal) + } + } + + // MARK: - Subviews + /// title + lazy var titleLabel: UILabel = { + let label = UILabel() + label.font = UIFont.systemFont(ofSize: 15, weight: .semibold) + label.textColor = UIColor(hexStr: "#0E0E0E") + return label + }() + + /// close + lazy var closeBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Common/close"), for: .normal) + btn.contentEdgeInsets = UIEdgeInsets(top: 7.5, left: 7.5, bottom: 7.5, right: 7.5) + btn.addTouchBlock { [weak self] _ in + self?.dismiss(animated: true) + } + btn.isHidden = true + return btn + }() + + /// text + lazy var contentLabel: UILabel = { + let label = UILabel() + label.font = UIFont.systemFont(ofSize: 13, weight: .medium) + label.textColor = UIColor(hexStr: "#0E0E0E") + label.numberOfLines = 0 + return label + }() + + /// + lazy var stackView: UIStackView = { + let view = UIStackView(arrangedSubviews: [cancelBtn, confirmBtn]) + view.spacing = 10 + view.axis = .horizontal + view.alignment = .fill + view.distribution = .fillEqually + return view + }() + + /// 确认 + lazy var cancelBtn: UIButton = { + let btn = UIButton() + btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .heavy) + btn.setTitle("oapp_Cancel".localizedString, for: .normal) + btn.setTitleColor(UIColor(hexStr: "#0E0E0E"), for: .normal) + btn.layer.borderWidth = 1 + btn.layer.borderColor = UIColor(hexStr: "#0E0E0E").cgColor + btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) + btn.setBackgroundColor(UIColor(hexStr: "#F5F5F5"), for: .normal) + btn.addTouchBlock { [weak self] _ in + self?.dismiss(animated: true, completion: { + self?.cancelBlock?() + }) + } + return btn + }() + + /// 确认 + lazy var confirmBtn: UIButton = { + let btn = UIButton() + btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .heavy) + btn.setTitle("oapp_Confirm".localizedString, for: .normal) + btn.setTitleColor(.white, for: .normal) + btn.setBackgroundColor(ThemeManager.shared.color.mainColor, for: .normal) + btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) + btn.addTouchBlock { [weak self] _ in + self?.dismiss(animated: true, completion: { + self?.confirmBlock?() + }) + } + return btn + }() + + // MARK: - Lifecycle + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + popStyle = .center + centerContentInset = 10 + centerCornerRadius = 0 + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public override func viewDidLoad() { + super.viewDidLoad() + + setupSubviews() + setupLayout() + } + +} + +// MARK: - Setup +private extension DLAlertPopVC { + + private func setupSubviews() { + + contentView.addSubview(closeBtn) + + if titleText != nil, + titleText?.isEmpty == false { + contentView.addSubview(titleLabel) + } + + if contentText != nil, + contentText?.isEmpty == false { + contentView.addSubview(contentLabel) + } + + if cancelText?.isEmpty == false || confirmText?.isEmpty == false { + contentView.addSubview(stackView) + } + + cancelBtn.isHidden = !(cancelText?.isEmpty == false) + confirmBtn.isHidden = !(confirmText?.isEmpty == false) + + } + + private func setupLayout() { + + + closeBtn.layoutChain + .top(5) + .right(5) + .size(CGSize(width: 30, height: 30)) + + var tempView: UIView? + if titleText != nil, + titleText?.isEmpty == false { + titleLabel.layoutChain + .left(15) + .top(15) + .rightToLeftOfView(closeBtn, offset: -10) + tempView = titleLabel + } + + if contentText != nil, + contentText?.isEmpty == false { + + if let tempView = tempView { + contentLabel.layoutChain + .left(15) + .right(15) + .topToBottomOfView(tempView, offset: 25) + } else { + contentLabel.layoutChain + .top(15) + .left(15) + .rightToLeftOfView(closeBtn, offset: -10) + } + tempView = contentLabel + } + + guard let tempView = tempView else { return } + if cancelText?.isEmpty == false || confirmText?.isEmpty == false { + stackView.layoutChain + .topToBottomOfView(tempView, offset: 30) + .left(15) + .right(15) + .bottom(15) + .height(44) + } + } +} + +// MARK: - Public +extension DLAlertPopVC { + +} + +// MARK: - Request +private extension DLAlertPopVC { + +} + +// MARK: - Action +@objc private extension DLAlertPopVC { + +} + +// MARK: - Private +private extension DLAlertPopVC { + +} + + +public extension UIViewController { + + /// 显示弹窗 + /// - Parameters: + /// - title: 标题 + /// - message: 文本内容 + /// - confirmText: 确认按钮文案 + /// - confirmBlock: 确认按钮点击回调 + /// - cancelText: 取消按钮文案 + /// - cancelBlock: 取消按钮点击回调 + func showAlert(showCloseBtn: Bool = true, + title: String?=nil, + message: String?=nil, + confirmText: String?=nil, + confirmBlock: (() -> Void)?=nil, + cancelText: String?=nil, + cancelBlock: (() -> Void)?=nil) { + if title == nil && message == nil { return } + let vc = DLAlertPopVC() + vc.titleText = title + vc.contentText = message + vc.confirmText = confirmText + vc.confirmBlock = confirmBlock + vc.cancelText = cancelText + vc.cancelBlock = cancelBlock + vc.closeBtn.isHidden = !showCloseBtn + vc.dimmingClick = showCloseBtn + present(vc, animated: true) + } + + static func showAlert(showCloseBtn: Bool = true, + title: String?=nil, + message: String?=nil, + confirmText: String?=nil, + confirmBlock: (() -> Void)?=nil, + cancelText: String?=nil, + cancelBlock: (() -> Void)?=nil) { + if title == nil && message == nil { return } + let vc = DLAlertPopVC() + vc.titleText = title + vc.contentText = message + vc.confirmText = confirmText + vc.confirmBlock = confirmBlock + vc.cancelText = cancelText + vc.cancelBlock = cancelBlock + vc.closeBtn.isHidden = !showCloseBtn + vc.dimmingClick = showCloseBtn + UIViewController.topMost?.present(vc, animated: true) + } +} diff --git a/QuickLocation/UIKit/Pop/DLCustomPopVC.swift b/QuickLocation/UIKit/Pop/DLCustomPopVC.swift new file mode 100644 index 00000000..daf0c2e7 --- /dev/null +++ b/QuickLocation/UIKit/Pop/DLCustomPopVC.swift @@ -0,0 +1,157 @@ +// +// ZWStandardPopVC.swift +// ZWStandardSDK +// +// Created by JH on 2022/11/21. +// + +import UIKit + +/// 底部|中心弹窗控制器基类,自动撑开 +open class DLCustomPopVC: UIViewController { + + // MARK: - Style + /// 弹窗样式 + public enum Style: Int { + /// 底部弹窗 + case bottom + /// 中心弹窗 + case center + } + + // MARK: - Accessor + /// 自定义弹窗位置,默认底部,需在viewDidLoad之前设置生效 + open var popStyle: Style = .bottom { + didSet { + updatePopStyle() + } + } + + /// 底部弹窗时是否允许侧滑关闭,默认false + open var screenEdgeEnabled: Bool = false { + didSet { + updatePopStyle() + } + } + /// 动画执行时间 + open var transitionDuration: CGFloat = 0.25 { + didSet { + updatePopStyle() + } + } + /// 是否可点击背景关闭界面,默认true + open var dimmingClick: Bool = true { + didSet { + backgroundView.isUserInteractionEnabled = dimmingClick + } + } + /// 暗色背景颜色,默认黑色,透明度0.4 + open var dimmingColor: UIColor? = UIColor.black.withAlphaComponent(0.3) { + didSet { + backgroundView.backgroundColor = dimmingColor + } + } + /// 点击背景关闭回调,默认nil + open var dimmingBlock: (() -> Void)? + + /// 自定义底部圆角大小,默认16,自动relative + open var bottomCornerRadius: CGFloat = 16 + /// 自定义中心圆角大小,默认16,自动relative + open var centerCornerRadius: CGFloat = 16 + /// 自定义中心内容边距,默认32,自动relative + open var centerContentInset: CGFloat = 32 + + // MARK: - Subviews + /// 背景视图,默认可点击背景关闭 + private lazy var backgroundView: UIView = { + let view = UIView() + view.backgroundColor = .clear + view.isUserInteractionEnabled = dimmingClick + view.addTapGestrue { [weak self] _ in + self?.dismiss(animated: true, completion: self?.dimmingBlock) + } + return view + }() + + /// 内容视图,高度须内部撑开 + public lazy var contentView: UIView = { + let view = UIView() + view.backgroundColor = UIColor.white + return view + }() + + // MARK: - Lifecyle + public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + + modalPresentationStyle = .custom + updatePopStyle() + } + + public required init?(coder: NSCoder) { + super.init(coder: coder) + + modalPresentationStyle = .custom + updatePopStyle() + } + + open override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .clear + + view.addSubview(backgroundView) + view.addSubview(contentView) + + backgroundView.layoutChain.edges() + if popStyle == .bottom { + contentView.layoutChain + .left() + .right() + .bottom() + } else { + contentView.layoutChain + .centerY() + .left(centerContentInset) + .right(centerContentInset) + } + } + + deinit { + debugPrint(self, #function) + } + + open override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + + if popStyle == .bottom { + let cornerLayer = CAShapeLayer() + let path = UIBezierPath(roundedRect: contentView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: bottomCornerRadius, height: bottomCornerRadius)) + cornerLayer.frame = contentView.bounds + cornerLayer.path = path.cgPath + contentView.layer.mask = cornerLayer + } else { + contentView.layer.masksToBounds = true + contentView.layer.cornerRadius = centerCornerRadius + } + } + + // MARK: - Private + private func updatePopStyle() { + if popStyle == .bottom { + let transition = __dl_setPresentTransition { [weak self] presentation in + presentation.dimmingColor = self?.dimmingColor + } + if screenEdgeEnabled { + transition.interactEnabled = true + transition.interactScreenEdge = true + } + transition.transitionDuration = transitionDuration + } else { + let transition = __dl_setAlertTransition { [weak self] presentation in + presentation.dimmingColor = self?.dimmingColor + } + transition.transitionDuration = transitionDuration + } + } + +} diff --git a/QuickLocation/UIKit/Pop/DLSheetPopVC.swift b/QuickLocation/UIKit/Pop/DLSheetPopVC.swift new file mode 100644 index 00000000..ab555ca1 --- /dev/null +++ b/QuickLocation/UIKit/Pop/DLSheetPopVC.swift @@ -0,0 +1,116 @@ +// +// DLSheetPopVC.swift +// dinoGo +// +// Created by 向浩 on 2022/12/2. +// Copyright © 2022 dino. All rights reserved. +// + +import Foundation +import UIKit + +public class DLSheetPopVC: DLCustomPopVC { + + lazy var titleLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 16, weight: .medium) + label.textColor = UIColor(hexStr: "#0E0E0E") + return label + }() + + lazy var contentLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 13, weight: .regular) + label.textColor = UIColor(hexStr: "#0E0E0E") + label.numberOfLines = 0 + return label + }() + + lazy var closeBtn: UIButton = { + let btn = UIButton(type: .custom) + btn.setImage(UIImage(named: "Common/close")?.image(scaleSize: CGSize(width: 12, height: 12)), for: .normal) + btn.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) + btn.addTouchBlock { [weak self] _ in + self?.dismiss(animated: true) + } + return btn + }() + + lazy var lineView: UIView = { + let view = UIView() + view.backgroundColor = UIColor(hexStr: "#F4F4F4") + return view + }() + + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + popStyle = .bottom + bottomCornerRadius = 10 + dimmingClick = false + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + + public override func viewDidLoad() { + super.viewDidLoad() + setupSubViews() + setupLayout() + } +} + +// MARK: - UI +private extension DLSheetPopVC { + + func setupSubViews() { + contentView.addSubview(titleLabel) + contentView.addSubview(closeBtn) + contentView.addSubview(lineView) + contentView.addSubview(contentLabel) + } + + func setupLayout() { + titleLabel.layoutChain + .left(15, relation: .greaterThanOrEqual) + .top(15) + .centerX() + + closeBtn.layoutChain + .centerY(titleLabel) + .right(6) + .size(CGSize(width: 28, height: 28)) + .leftToRightOfView(titleLabel, offset: 10, relation: .greaterThanOrEqual) + + lineView.layoutChain + .topToBottomOfView(titleLabel, offset: 15) + .left() + .right() + .height(0.5) + + contentLabel.layoutChain + .topToBottomOfView(lineView, offset: 15) + .left(15) + .right(15) + .bottom(15, relation: .greaterThanOrEqual) + + contentView.layoutChain + .height(kScreenHeight * 0.35, relation: .greaterThanOrEqual) + } +} + +public extension UIViewController { + + /// 显示底部弹窗 + /// - Parameters: + /// - title: 标题 + /// - subTitle: 自标题 + func showSheet(title: String, subTitle: String) { + let vc = DLSheetPopVC() + vc.titleLabel.text = title + vc.contentLabel.text = subTitle + present(vc, animated: true) + } + +} diff --git a/QuickLocation/UIKit/Pop/DLViewTransition.h b/QuickLocation/UIKit/Pop/DLViewTransition.h new file mode 100644 index 00000000..7fd4c9aa --- /dev/null +++ b/QuickLocation/UIKit/Pop/DLViewTransition.h @@ -0,0 +1,273 @@ +// +// FWViewTransition.h +// DLSDK +// +// Created by osell on 2022/8/23. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - DLAnimatedTransitionType + +/** + 转场动画类型 + + @const DLAnimatedTransitionTypeNone 转场未开始 + @const DLAnimatedTransitionTypePush push转场 + @const DLAnimatedTransitionTypePop pop转场 + @const DLAnimatedTransitionTypePresent present转场 + @const DLAnimatedTransitionTypeDismiss dismiss转场 + */ +typedef NS_ENUM(NSInteger, DLAnimatedTransitionType) { + DLAnimatedTransitionTypeNone = 0, + FWAnimatedTransitionTypePush, + FWAnimatedTransitionTypePop, + FWAnimatedTransitionTypePresent, + FWAnimatedTransitionTypeDismiss, +} NS_SWIFT_NAME(AnimatedTransitionType); + +#pragma mark - DLAnimatedTransition + +/// 转场动画类,默认透明度变化 +NS_SWIFT_NAME(AnimatedTransition) +@interface DLAnimatedTransition : UIPercentDrivenInteractiveTransition + +#pragma mark - Public + +/// 创建系统转场单例,不支持交互手势转场 ++ (instancetype)systemTransition; + +/// 创建动画句柄转场 ++ (instancetype)transitionWithBlock:(nullable void (^)(DLAnimatedTransition *transition))block; + +/// 设置动画句柄 +@property (nullable, nonatomic, copy) void (^transitionBlock)(DLAnimatedTransition *transition); + +/// 动画持续时间,必须大于0,默认0.35秒(默认设置completionSpeed为0.35) +@property (nonatomic, assign) NSTimeInterval transitionDuration; + +/// 获取动画类型,默认根据上下文判断 +@property (nonatomic, assign) DLAnimatedTransitionType transitionType; + +#pragma mark - Interactive + +/// 是否启用交互pan手势进行pop|dismiss,默认NO。可使用父类属性设置交互动画 +@property (nonatomic, assign) BOOL interactEnabled; + +/// 是否启用screenEdge交互手势,默认NO,gestureRecognizer加载前设置生效 +@property (nonatomic, assign) BOOL interactScreenEdge; + +/// 指定交互pan手势对象,默认FWPanGestureRecognizer,可设置交互方向,滚动视图等 +@property (nonatomic, strong) __kindof UIPanGestureRecognizer *gestureRecognizer; + +/// 是否正在交互中,手势开始才会标记为YES,手势结束标记为NO +@property (nonatomic, assign, readonly) BOOL isInteractive; + +/// 自定义交互句柄,可根据手势state处理不同状态的交互,返回YES执行默认交互,返回NO不执行。默认为空,执行默认交互 +@property (nullable, nonatomic, copy) BOOL(^interactBlock)(__kindof UIPanGestureRecognizer *gestureRecognizer); + +/// 自定义dismiss关闭动画完成回调,默认nil +@property (nullable, nonatomic, copy) void(^dismissCompletion)(void); + +/// 手工绑定交互控制器,添加pan手势,需要vc.view存在时调用才生效。默认自动绑定,如果自定义interactBlock,必须手工绑定 +- (void)interactWith:(UIViewController *)viewController; + +#pragma mark - Presentation + +/// 是否启用默认展示控制器,启用后自动设置presentationBlock返回FWPresentationController,默认NO +@property (nonatomic, assign) BOOL presentationEnabled; + +/// 设置展示控制器创建句柄,自定义弹出效果。present时建议设置modalPresentationStyle为Custom +@property (nullable, nonatomic, copy) UIPresentationController *(^presentationBlock)(UIViewController *presented, UIViewController *presenting); + +#pragma mark - Animate + +/// 转场上下文,只读 +@property (nullable, nonatomic, weak, readonly) id transitionContext; + +/// 标记动画开始(自动添加视图到容器) +- (void)start; + +/// 执行动画,子类重写,可选 +- (void)animate; + +/// 自动标记动画完成(根据transitionContext是否被取消判断) +- (void)complete; + +@end + +#pragma mark - DLSwipeAnimatedTransition + +/// 滑动转场动画类,默认上下 +NS_SWIFT_NAME(SwipeAnimatedTransition) +@interface DLSwipeAnimatedTransition : DLAnimatedTransition + +/// 创建滑动转场,指定进入(push|present)和消失(pop|dismiss)方向 ++ (instancetype)transitionWithInDirection:(UISwipeGestureRecognizerDirection)inDirection + outDirection:(UISwipeGestureRecognizerDirection)outDirection; + +/// 指定进入(push|present)方向,默认上滑Up +@property (nonatomic, assign) UISwipeGestureRecognizerDirection inDirection; +/// 指定消失(pop|dismiss)方向,默认下滑Down +@property (nonatomic, assign) UISwipeGestureRecognizerDirection outDirection; + +@end + +#pragma mark - DLTransformAnimatedTransition + +/// 形变转场动画类,默认缩放 +NS_SWIFT_NAME(TransformAnimatedTransition) +@interface DLTransformAnimatedTransition : DLAnimatedTransition + +/// 创建形变转场,指定进入(push|present)和消失(pop|dismiss)形变 ++ (instancetype)transitionWithInTransform:(CGAffineTransform)inTransform + outTransform:(CGAffineTransform)outTransform; + +/// 指定进入(push|present)形变,默认缩放0.01 +@property (nonatomic, assign) CGAffineTransform inTransform; +/// 指定消失(pop|dismiss)形变,默认缩放0.01 +@property (nonatomic, assign) CGAffineTransform outTransform; + +@end + +#pragma mark - DLPresentationController + +/// 自定义展示控制器。默认显示暗色背景动画且弹出视图占满容器,可通过属性自定义 +NS_SWIFT_NAME(PresentationController) +@interface DLPresentationController : UIPresentationController + +/// 是否显示暗色背景,默认YES +@property (nonatomic, assign) BOOL showDimming; +/// 是否可以点击暗色背景关闭,默认YES。如果弹出视图占满容器,手势不生效(因为弹出视图挡住了暗色背景) +@property (nonatomic, assign) BOOL dimmingClick; +/// 是否执行暗黑背景透明度动画,默认YES +@property (nonatomic, assign) BOOL dimmingAnimated; +/// 暗色背景颜色,默认黑色,透明度0.5 +@property (nonatomic, strong, nullable) UIColor *dimmingColor; +/// 设置点击暗色背景关闭完成回调,默认nil +@property (nonatomic, copy, nullable) void (^dismissCompletion)(void); + +/// 设置弹出视图的圆角位置,默认左上和右上。如果弹出视图占满容器,不生效需弹出视图自定义 +@property (nonatomic, assign) UIRectCorner rectCorner; +/// 设置弹出视图的圆角半径,默认0无圆角。如果弹出视图占满容器,不生效需弹出视图自定义 +@property (nonatomic, assign) CGFloat cornerRadius; + +/// 自定义弹出视图的frame计算block,默认nil占满容器,优先级高 +@property (nonatomic, copy, nullable) CGRect (^frameBlock)(DLPresentationController *presentationController); +/// 设置弹出视图的frame,默认CGRectZero占满容器,优先级中 +@property (nonatomic, assign) CGRect presentedFrame; +/// 设置弹出视图的居中size,默认CGSizeZero占满容器,优先级中 +@property (nonatomic, assign) CGSize presentedSize; +/// 设置弹出视图的顶部距离,默认0占满容器,优先级低 +@property (nonatomic, assign) CGFloat verticalInset; + +@end + +#pragma mark - DLPanGestureRecognizer + +/** + FWPanGestureRecognizer + @note 自动处理与滚动视图pan手势在指定方向的冲突,默认设置delegate为自身。如果找到滚动视图则处理之,否则同父类 + */ +NS_SWIFT_NAME(PanGestureRecognizer) +@interface DLPanGestureRecognizer : UIPanGestureRecognizer + +/// 是否自动检测滚动视图,默认YES。如需手工指定,请禁用之 +@property (nonatomic, assign) BOOL autoDetected; + +/// 是否按下就立即转换Began状态,默认NO,需要等待移动才会触发Began +@property (nonatomic, assign) BOOL instantBegan; + +/// 指定滚动视图,自动处理与滚动视图pan手势在指定方向的冲突。自动设置默认delegate为自身 +@property (nullable, nonatomic, weak) UIScrollView *scrollView; + +/// 指定与滚动视图pan手势的冲突交互方向,默认向下 +@property (nonatomic, assign) UISwipeGestureRecognizerDirection direction; + +/// 获取当前手势在指定交互方向的滑动进度 +@property (nonatomic, assign) CGFloat swipePercent; + +/// 指定当前手势在指定交互方向的最大识别距离,默认0,无限制 +@property (nonatomic, assign) CGFloat maximumDistance; + +/// 自定义Failed判断句柄。默认判定失败时直接修改状态为Failed,可设置此block修改判定条件 +@property (nullable, nonatomic, copy) BOOL (^shouldFailed)(DLPanGestureRecognizer *gestureRecognizer); + +/// 自定义shouldBegin判断句柄 +@property (nullable, nonatomic, copy) BOOL (^shouldBegin)(DLPanGestureRecognizer *gestureRecognizer); + +/// 自定义shouldBeRequiredToFail判断句柄 +@property (nullable, nonatomic, copy) BOOL (^shouldBeRequiredToFail)(UIGestureRecognizer *otherGestureRecognizer); + +/// 自定义shouldRequireFailure判断句柄 +@property (nullable, nonatomic, copy) BOOL (^shouldRequireFailure)(UIGestureRecognizer *otherGestureRecognizer); + +@end + +#pragma mark - UIViewController+DLTransition + +/// 视图控制器转场分类,如需半透明,请在init中设置modalPresentationStyle为UIModalPresentationCustom(注意不会触发原控制器viewWillDisappear:) +@interface UIViewController (DLTransition) + +/// 视图控制器present|dismiss转场。注意会修改transitioningDelegate,且会强引用之;如需weak引用,请直接设置transitioningDelegate +@property (nullable, nonatomic, strong) DLAnimatedTransition *dl_modalTransition NS_REFINED_FOR_SWIFT; + +/// 视图控制器push|pop转场,代理导航控制器转场,需在fwNavigationTransition设置后生效 +@property (nullable, nonatomic, strong) DLAnimatedTransition *dl_viewTransition NS_REFINED_FOR_SWIFT; + +/// 自定义控制器present系统转场(蒙层渐变,内容向上动画),会设置fwModalTransition +- (DLAnimatedTransition *)dl_setPresentTransition:(nullable void (^)(DLPresentationController *))presentationBlock NS_REFINED_FOR_SWIFT; + +/// 自定义控制器alert缩放转场(蒙层渐变,内容缩放动画),会设置fwModalTransition +- (DLAnimatedTransition *)dl_setAlertTransition:(nullable void (^)(DLPresentationController *))presentationBlock NS_REFINED_FOR_SWIFT; + +/// 自定义控制器fade渐变转场(蒙层和内容渐变动画),会设置fwModalTransition; +- (DLAnimatedTransition *)dl_setFadeTransition:(nullable void (^)(DLPresentationController *))presentationBlock NS_REFINED_FOR_SWIFT; + +/// 设置iOS13默认present手势下拉dismiss时的回调block,仅iOS13生效,自动触发,手工dismiss不会触发。会自动设置presentationController.delegate +@property (nonatomic, copy, nullable) void (^dl_presentationDidDismiss)(void) NS_REFINED_FOR_SWIFT; + +/// 自定义控制器popover弹出效果(preferredContentSize设置大小),会自动设置modalPresentationStyle和popoverPresentationController.delegate +- (void)dl_setPopoverPresentation:(void (NS_NOESCAPE ^ _Nullable)(UIPopoverPresentationController *))presentationBlock shouldDismiss:(BOOL)shouldDismiss NS_REFINED_FOR_SWIFT; + +@end + +#pragma mark - UIView+DLTransition + +/// 自定义视图模拟转场分类 +@interface UIView (DLTransition) + +/// 转场添加到指定控制器(pinEdges占满父视图),返回父容器视图。VC.tabBarController.view > VC.navigationController.view > VC.view +- (UIView *)dl_transitionToController:(UIViewController *)viewController pinEdges:(BOOL)pinEdges NS_REFINED_FOR_SWIFT; + +/// 包装到转场控制器(pinEdges占满父视图),返回创建的控制器 +- (UIViewController *)dl_wrappedTransitionController:(BOOL)pinEdges NS_REFINED_FOR_SWIFT; + +/// 自定义视图模拟present系统转场(蒙层渐变,内容向上动画) +- (void)dl_setPresentTransition:(DLAnimatedTransitionType)transitionType + contentView:(nullable UIView *)contentView + completion:(nullable void (^)(BOOL finished))completion NS_REFINED_FOR_SWIFT; + +/// 自定义视图模拟alert缩放转场(蒙层渐变,内容缩放动画) +- (void)dl_setAlertTransition:(DLAnimatedTransitionType)transitionType + completion:(nullable void (^)(BOOL finished))completion NS_REFINED_FOR_SWIFT; + +/// 自定义视图模拟fade渐变转场(蒙层和内容渐变动画) +- (void)dl_setFadeTransition:(DLAnimatedTransitionType)transitionType + completion:(nullable void (^)(BOOL finished))completion NS_REFINED_FOR_SWIFT; + +@end + +#pragma mark - UINavigationController+DLTransition + +/// 导航控制器转场分类 +@interface UINavigationController (DLTransition) + +/// 导航控制器push|pop转场。注意会修改delegate,且会强引用之,一直生效直到设置为nil。如需weak引用,请直接设置delegate +@property (nullable, nonatomic, strong) DLAnimatedTransition *dl_navigationTransition NS_REFINED_FOR_SWIFT; + +@end + +NS_ASSUME_NONNULL_END diff --git a/QuickLocation/UIKit/Pop/DLViewTransition.m b/QuickLocation/UIKit/Pop/DLViewTransition.m new file mode 100644 index 00000000..537213bf --- /dev/null +++ b/QuickLocation/UIKit/Pop/DLViewTransition.m @@ -0,0 +1,1228 @@ +// +// FWViewTransition.m +// DLSDK +// +// Created by osell on 2022/8/23. +// + +#import "DLViewTransition.h" +#import + +#pragma mark - DLAnimatedTransition + +@interface DLAnimatedTransition () + +@property (nonatomic, assign) BOOL isSystem; + +@property (nonatomic, weak) id transitionContext; + +@property (nonatomic, copy) void(^interactBegan)(void); + +@end + +@implementation DLAnimatedTransition + +@synthesize gestureRecognizer = _gestureRecognizer; + +#pragma mark - Lifecycle + ++ (instancetype)systemTransition +{ + static DLAnimatedTransition *instance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + instance = [[DLAnimatedTransition alloc] init]; + instance.isSystem = YES; + }); + return instance; +} + ++ (instancetype)transitionWithBlock:(void (^)(DLAnimatedTransition *))block +{ + DLAnimatedTransition *transition = [[self alloc] init]; + transition.transitionBlock = block; + return transition; +} + +- (instancetype)init +{ + self = [super init]; + if (self) { + _transitionDuration = 0.35; + self.completionSpeed = 0.35; + } + return self; +} + +#pragma mark - Private + +- (void)setInteractEnabled:(BOOL)enabled +{ + _interactEnabled = enabled; + _gestureRecognizer.enabled = enabled; +} + +- (void)interactWith:(UIViewController *)viewController +{ + if (!viewController.view) return; + + for (UIGestureRecognizer *gestureRecognizer in viewController.view.gestureRecognizers) { + if (gestureRecognizer == self.gestureRecognizer) return; + } + [viewController.view addGestureRecognizer:self.gestureRecognizer]; +} + +- (__kindof UIPanGestureRecognizer *)gestureRecognizer +{ + if (!_gestureRecognizer) { + if (self.interactScreenEdge) { + UIScreenEdgePanGestureRecognizer *gestureRecognizer = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognizerAction:)]; + gestureRecognizer.edges = UIRectEdgeLeft; + _gestureRecognizer = gestureRecognizer; + } else { + _gestureRecognizer = [[DLPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognizerAction:)]; + } + } + return _gestureRecognizer; +} + +- (void)setGestureRecognizer:(__kindof UIPanGestureRecognizer *)gestureRecognizer +{ + _gestureRecognizer = gestureRecognizer; + [gestureRecognizer addTarget:self action:@selector(gestureRecognizerAction:)]; +} + +- (void)gestureRecognizerAction:(UIPanGestureRecognizer *)gestureRecognizer +{ + switch (gestureRecognizer.state) { + case UIGestureRecognizerStateBegan: { + _isInteractive = YES; + + BOOL interactBegan = self.interactBlock ? self.interactBlock(gestureRecognizer) : YES; + if (interactBegan && self.interactBegan) { + self.interactBegan(); + } + break; + } + case UIGestureRecognizerStateChanged: { + BOOL interactChanged = self.interactBlock ? self.interactBlock(gestureRecognizer) : YES; + if (interactChanged) { + CGFloat percent; + if ([gestureRecognizer isKindOfClass:[DLPanGestureRecognizer class]]) { + percent = [(DLPanGestureRecognizer *)gestureRecognizer swipePercent]; + } else { + CGPoint transition = [gestureRecognizer translationInView:gestureRecognizer.view]; + percent = MAX(0, MIN(1, transition.x / gestureRecognizer.view.bounds.size.width)); + } + + [self updateInteractiveTransition:percent]; + } + break; + } + case UIGestureRecognizerStateCancelled: + case UIGestureRecognizerStateFailed: + case UIGestureRecognizerStateEnded: { + _isInteractive = NO; + + BOOL interactEnded = self.interactBlock ? self.interactBlock(gestureRecognizer) : YES; + if (interactEnded) { + BOOL finished = NO; + if (gestureRecognizer.state == UIGestureRecognizerStateCancelled || + gestureRecognizer.state == UIGestureRecognizerStateFailed) { + finished = NO; + } else if (self.percentComplete >= 0.5) { + finished = YES; + } else if ([gestureRecognizer isKindOfClass:[DLPanGestureRecognizer class]]) { + CGPoint velocity = [gestureRecognizer velocityInView:gestureRecognizer.view]; + CGPoint transition = [gestureRecognizer translationInView:gestureRecognizer.view]; + switch (((DLPanGestureRecognizer *)gestureRecognizer).direction) { + case UISwipeGestureRecognizerDirectionUp: + if (velocity.y <= -100 && fabs(transition.x) < fabs(transition.y)) finished = YES; + break; + case UISwipeGestureRecognizerDirectionLeft: + if (velocity.x <= -100 && fabs(transition.x) > fabs(transition.y)) finished = YES; + break; + case UISwipeGestureRecognizerDirectionDown: + if (velocity.y >= 100 && fabs(transition.x) < fabs(transition.y)) finished = YES; + break; + case UISwipeGestureRecognizerDirectionRight: + if (velocity.x >= 100 && fabs(transition.x) > fabs(transition.y)) finished = YES; + break; + default: + break; + } + } else { + CGPoint velocity = [gestureRecognizer velocityInView:gestureRecognizer.view]; + CGPoint transition = [gestureRecognizer translationInView:gestureRecognizer.view]; + if (velocity.x >= 100 && fabs(transition.x) > fabs(transition.y)) finished = YES; + } + + if (finished) { + [self finishInteractiveTransition]; + } else { + [self cancelInteractiveTransition]; + } + } + break; + } + default: + break; + } +} + +- (BOOL)presentationEnabled +{ + return self.presentationBlock != nil; +} + +- (void)setPresentationEnabled:(BOOL)enabled +{ + if (enabled == self.presentationEnabled) return; + + if (enabled) { + self.presentationBlock = ^UIPresentationController *(UIViewController *presented, UIViewController *presenting) { + return [[DLPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting]; + }; + } else { + self.presentationBlock = nil; + } +} + +- (id)interactiveTransitionForTransition:(id)transition +{ + if (self.transitionType == FWAnimatedTransitionTypeDismiss || self.transitionType == FWAnimatedTransitionTypePop) { + if (!self.isSystem && self.interactEnabled && self.isInteractive) { + return self; + } + } + return nil; +} + +#pragma mark - UIViewControllerTransitioningDelegate + +- (id)animationControllerForPresentedController:(UIViewController *)presented + presentingController:(UIViewController *)presenting + sourceController:(UIViewController *)source +{ + self.transitionType = FWAnimatedTransitionTypePresent; + // 自动设置和绑定dismiss交互转场,在dismiss前设置生效 + if (!self.isSystem && self.interactEnabled && !self.interactBlock) { + __weak UIViewController *weakPresented = presented; + self.interactBegan = ^{ + [weakPresented dismissViewControllerAnimated:YES completion:nil]; + }; + [self interactWith:presented]; + } + return !self.isSystem ? self : nil; +} + +- (id)animationControllerForDismissedController:(UIViewController *)dismissed +{ + self.transitionType = FWAnimatedTransitionTypeDismiss; + return !self.isSystem ? self : nil; +} + +- (id)interactionControllerForPresentation:(id)animator +{ + return [self interactiveTransitionForTransition:animator]; +} + +- (id)interactionControllerForDismissal:(id)animator +{ + return [self interactiveTransitionForTransition:animator]; +} + +- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source +{ + if (self.presentationBlock) { + return self.presentationBlock(presented, presenting); + } + return nil; +} + +#pragma mark - UINavigationControllerDelegate + +- (id)navigationController:(UINavigationController *)navigationController + animationControllerForOperation:(UINavigationControllerOperation)operation + fromViewController:(UIViewController *)fromVC + toViewController:(UIViewController *)toVC +{ + if (operation == UINavigationControllerOperationPush) { + // push时检查toVC的转场代理 + DLAnimatedTransition *transition = toVC.dl_viewTransition ?: self; + transition.transitionType = FWAnimatedTransitionTypePush; + // 自动设置和绑定pop交互转场,在pop前设置生效 + if (!transition.isSystem && transition.interactEnabled && !transition.interactBlock) { + transition.interactBegan = ^{ + [navigationController popViewControllerAnimated:YES]; + }; + [transition interactWith:toVC]; + } + return !transition.isSystem ? transition : nil; + } else if (operation == UINavigationControllerOperationPop) { + // pop时检查fromVC的转场代理 + DLAnimatedTransition *transition = fromVC.dl_viewTransition ?: self; + transition.transitionType = FWAnimatedTransitionTypePop; + return !transition.isSystem ? transition : nil; + } + return nil; +} + +- (id )navigationController:(UINavigationController *)navigationController + interactionControllerForAnimationController:(id ) animationController +{ + return [self interactiveTransitionForTransition:animationController]; +} + +#pragma mark - UIViewControllerAnimatedTransitioning + +- (NSTimeInterval)transitionDuration:(id)transitionContext +{ + return transitionContext.isAnimated ? self.transitionDuration : 0.f; +} + +- (void)animateTransition:(id)transitionContext +{ + self.transitionContext = transitionContext; + + if (self.transitionBlock) { + self.transitionBlock(self); + } else { + [self animate]; + } +} + +#pragma mark - Animate + +- (DLAnimatedTransitionType)transitionType +{ + // 如果自定义type,优先使用之 + if (_transitionType != DLAnimatedTransitionTypeNone) { + return _transitionType; + } + + // 自动根据上下文获取type + if (!self.transitionContext) { + return DLAnimatedTransitionTypeNone; + } + + UIViewController *fromViewController = [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; + UIViewController *toViewController = [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; + // 导航栏为同一个时为push|pop + if (fromViewController.navigationController && toViewController.navigationController && + fromViewController.navigationController == toViewController.navigationController) { + NSInteger toIndex = [toViewController.navigationController.viewControllers indexOfObject:toViewController]; + NSInteger fromIndex = [fromViewController.navigationController.viewControllers indexOfObject:fromViewController]; + if (toIndex > fromIndex) { + return FWAnimatedTransitionTypePush; + } else { + return FWAnimatedTransitionTypePop; + } + } else { + if (toViewController.presentingViewController == fromViewController) { + return FWAnimatedTransitionTypePresent; + } else { + return FWAnimatedTransitionTypeDismiss; + } + } +} + +- (void)start +{ + UIView *fromView = [self.transitionContext viewForKey:UITransitionContextFromViewKey]; + UIView *toView = [self.transitionContext viewForKey:UITransitionContextToViewKey]; + switch (self.transitionType) { + // push时fromView在下,toView在上 + case FWAnimatedTransitionTypePush: { + [self.transitionContext.containerView addSubview:fromView]; + [self.transitionContext.containerView addSubview:toView]; + break; + } + // pop时fromView在上,toView在下 + case FWAnimatedTransitionTypePop: { + // 此处后添加fromView,方便做pop动画,可自行移动toView到上面 + [self.transitionContext.containerView addSubview:toView]; + [self.transitionContext.containerView addSubview:fromView]; + break; + } + // present时使用toView做动画 + case FWAnimatedTransitionTypePresent: { + [self.transitionContext.containerView addSubview:toView]; + break; + } + // dismiss时使用fromView做动画 + case FWAnimatedTransitionTypeDismiss: { + [self.transitionContext.containerView addSubview:fromView]; + break; + } + default: { + break; + } + } +} + +- (void)animate +{ + // 子类可重写,默认alpha动画 + DLAnimatedTransitionType transitionType = [self transitionType]; + BOOL transitionIn = (transitionType == FWAnimatedTransitionTypePush || transitionType == FWAnimatedTransitionTypePresent); + UIView *transitionView = transitionIn ? [self.transitionContext viewForKey:UITransitionContextToViewKey] : [self.transitionContext viewForKey:UITransitionContextFromViewKey]; + + [self start]; + if (transitionIn) transitionView.alpha = 0; + [UIView animateWithDuration:[self transitionDuration:self.transitionContext] delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{ + transitionView.alpha = transitionIn ? 1 : 0; + } completion:^(BOOL finished) { + [self complete]; + }]; +} + +- (void)complete +{ + DLAnimatedTransitionType transitionType = [self transitionType]; + BOOL didComplete = ![self.transitionContext transitionWasCancelled]; + [self.transitionContext completeTransition:didComplete]; + + if (didComplete && self.dismissCompletion && + transitionType == FWAnimatedTransitionTypeDismiss) { + self.dismissCompletion(); + } +} + +@end + +#pragma mark - DLSwipeAnimatedTransition + +@implementation DLSwipeAnimatedTransition + ++ (instancetype)transitionWithInDirection:(UISwipeGestureRecognizerDirection)inDirection + outDirection:(UISwipeGestureRecognizerDirection)outDirection +{ + DLSwipeAnimatedTransition *transition = [[self alloc] init]; + transition.inDirection = inDirection; + transition.outDirection = outDirection; + return transition; +} + +- (instancetype)init +{ + self = [super init]; + if (self) { + _inDirection = UISwipeGestureRecognizerDirectionUp; + _outDirection = UISwipeGestureRecognizerDirectionDown; + } + return self; +} + +- (void)setOutDirection:(UISwipeGestureRecognizerDirection)outDirection +{ + _outDirection = outDirection; + if ([self.gestureRecognizer isKindOfClass:[DLPanGestureRecognizer class]]) { + ((DLPanGestureRecognizer *)self.gestureRecognizer).direction = outDirection; + } +} + +- (void)animate +{ + DLAnimatedTransitionType transitionType = [self transitionType]; + BOOL transitionIn = (transitionType == FWAnimatedTransitionTypePush || transitionType == FWAnimatedTransitionTypePresent); + UISwipeGestureRecognizerDirection direction = transitionIn ? self.inDirection : self.outDirection; + CGVector offset; + switch (direction) { + case UISwipeGestureRecognizerDirectionLeft: { + offset = CGVectorMake(-1.f, 0.f); + break; + } + case UISwipeGestureRecognizerDirectionRight: { + offset = CGVectorMake(1.f, 0.f); + break; + } + case UISwipeGestureRecognizerDirectionUp: { + offset = CGVectorMake(0.f, -1.f); + break; + } + case UISwipeGestureRecognizerDirectionDown: + default: { + offset = CGVectorMake(0.f, 1.f); + break; + } + } + + CGRect fromFrame = [self.transitionContext initialFrameForViewController:[self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]]; + CGRect toFrame = [self.transitionContext finalFrameForViewController:[self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]]; + UIView *fromView = [self.transitionContext viewForKey:UITransitionContextFromViewKey]; + UIView *toView = [self.transitionContext viewForKey:UITransitionContextToViewKey]; + if (transitionIn) { + [self.transitionContext.containerView addSubview:toView]; + toView.frame = [self animateFrameWithFrame:toFrame offset:offset initial:YES show:transitionIn]; + fromView.frame = fromFrame; + } else { + [self.transitionContext.containerView insertSubview:toView belowSubview:fromView]; + fromView.frame = [self animateFrameWithFrame:fromFrame offset:offset initial:YES show:transitionIn]; + toView.frame = toFrame; + } + + [UIView animateWithDuration:[self transitionDuration:self.transitionContext] animations:^{ + if (transitionIn) { + toView.frame = [self animateFrameWithFrame:toFrame offset:offset initial:NO show:transitionIn]; + } else { + fromView.frame = [self animateFrameWithFrame:fromFrame offset:offset initial:NO show:transitionIn]; + } + } completion:^(BOOL finished) { + if ([self.transitionContext transitionWasCancelled]) { + [toView removeFromSuperview]; + } + [self complete]; + }]; +} + +- (CGRect)animateFrameWithFrame:(CGRect)frame offset:(CGVector)offset initial:(BOOL)initial show:(BOOL)show +{ + NSInteger vectorValue = offset.dx == 0 ? offset.dy : offset.dx; + NSInteger flag = 0; + if (initial) { + vectorValue = vectorValue > 0 ? -vectorValue : vectorValue; + flag = show ? vectorValue : 0; + } else { + vectorValue = vectorValue > 0 ? vectorValue : -vectorValue; + flag = show ? 0 : vectorValue; + } + + CGFloat offsetX = frame.size.width * offset.dx * flag; + CGFloat offsetY = frame.size.height * offset.dy * flag; + return CGRectOffset(frame, offsetX, offsetY); +} + +@end + +#pragma mark - DLTransformAnimatedTransition + +@implementation DLTransformAnimatedTransition + ++ (instancetype)transitionWithInTransform:(CGAffineTransform)inTransform + outTransform:(CGAffineTransform)outTransform +{ + DLTransformAnimatedTransition *transition = [[self alloc] init]; + transition.inTransform = inTransform; + transition.outTransform = outTransform; + return transition; +} + +- (instancetype)init +{ + self = [super init]; + if (self) { + _inTransform = CGAffineTransformMakeScale(0.01, 0.01); + _outTransform = CGAffineTransformMakeScale(0.01, 0.01); + } + return self; +} + +- (void)animate +{ + DLAnimatedTransitionType transitionType = [self transitionType]; + BOOL transitionIn = (transitionType == FWAnimatedTransitionTypePush || transitionType == FWAnimatedTransitionTypePresent); + UIView *transitionView = transitionIn ? [self.transitionContext viewForKey:UITransitionContextToViewKey] : [self.transitionContext viewForKey:UITransitionContextFromViewKey]; + + [self start]; + if (transitionIn) { + transitionView.transform = self.inTransform; + transitionView.alpha = 0; + } + [UIView animateWithDuration:[self transitionDuration:self.transitionContext] delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{ + transitionView.transform = transitionIn ? CGAffineTransformIdentity : self.outTransform; + transitionView.alpha = transitionIn ? 1 : 0; + } completion:^(BOOL finished) { + [self complete]; + }]; +} + +@end + +#pragma mark - DLPresentationController + +@interface DLPresentationController () + +@property (nonatomic, strong) UIView *dimmingView; + +@end + +@implementation DLPresentationController + +#pragma mark - Lifecycle + +- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController +{ + self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController]; + if (self) { + _showDimming = YES; + _dimmingClick = YES; + _dimmingAnimated = YES; + _dimmingColor = [[UIColor blackColor] colorWithAlphaComponent:0.5]; + _rectCorner = UIRectCornerTopLeft | UIRectCornerTopRight; + _cornerRadius = 0; + _presentedFrame = CGRectZero; + _presentedSize = CGSizeZero; + _verticalInset = 0; + } + return self; +} + +#pragma mark - Accessor + +- (UIView *)dimmingView +{ + if (!_dimmingView) { + _dimmingView = [[UIView alloc] initWithFrame:self.containerView.bounds]; + _dimmingView.backgroundColor = self.dimmingColor; + + UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapAction:)]; + [_dimmingView addGestureRecognizer:tapGesture]; + } + return _dimmingView; +} + +- (void)setShowDimming:(BOOL)showDimming +{ + _showDimming = showDimming; + self.dimmingView.hidden = !showDimming; +} + +- (void)setDimmingClick:(BOOL)dimmingClick +{ + _dimmingClick = dimmingClick; + self.dimmingView.userInteractionEnabled = dimmingClick; +} + +- (void)onTapAction:(id)sender +{ + [self.presentedViewController dismissViewControllerAnimated:YES completion:self.dismissCompletion]; +} + +#pragma mark - Protected + +- (void)presentationTransitionWillBegin +{ + [super presentationTransitionWillBegin]; + + self.presentedView.frame = [self frameOfPresentedViewInContainerView]; + if (self.cornerRadius > 0) { + self.presentedView.layer.masksToBounds = YES; + if ((self.rectCorner & UIRectCornerAllCorners) == UIRectCornerAllCorners) { + self.presentedView.layer.cornerRadius = self.cornerRadius; + } else { + CAShapeLayer *cornerLayer = [CAShapeLayer layer]; + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.presentedView.bounds byRoundingCorners:self.rectCorner cornerRadii:CGSizeMake(self.cornerRadius, self.cornerRadius)]; + cornerLayer.frame = self.presentedView.bounds; + cornerLayer.path = path.CGPath; + self.presentedView.layer.mask = cornerLayer; + } + } + self.dimmingView.frame = self.containerView.bounds; + [self.containerView insertSubview:self.dimmingView atIndex:0]; + + if (self.dimmingAnimated) { + self.dimmingView.alpha = 0; + [self.presentingViewController.transitionCoordinator animateAlongsideTransition:^(id context) { + self.dimmingView.alpha = 1.0; + } completion:nil]; + } +} + +- (void)dismissalTransitionWillBegin +{ + [super dismissalTransitionWillBegin]; + + if (self.dimmingAnimated) { + [self.presentingViewController.transitionCoordinator animateAlongsideTransition:^(id context) { + self.dimmingView.alpha = 0; + } completion:nil]; + } +} + +- (void)dismissalTransitionDidEnd:(BOOL)completed +{ + [super dismissalTransitionDidEnd:completed]; + + if (completed) { + [self.dimmingView removeFromSuperview]; + } +} + +- (CGRect)frameOfPresentedViewInContainerView +{ + if (self.frameBlock) { + return self.frameBlock(self); + } else if (!CGRectEqualToRect(self.presentedFrame, CGRectZero)) { + return self.presentedFrame; + } else if (!CGSizeEqualToSize(self.presentedSize, CGSizeZero)) { + CGRect presentedFrame = CGRectMake(0, 0, self.presentedSize.width, self.presentedSize.height); + presentedFrame.origin.x = (self.containerView.bounds.size.width - self.presentedSize.width) / 2; + presentedFrame.origin.y = (self.containerView.bounds.size.height - self.presentedSize.height) / 2; + return presentedFrame; + } else if (self.verticalInset != 0) { + CGRect presentedFrame = self.containerView.bounds; + presentedFrame.origin.y = self.verticalInset; + presentedFrame.size.height -= self.verticalInset; + return presentedFrame; + } else { + return self.containerView.bounds; + } +} + +@end + +#pragma mark - DLPanGestureRecognizer + +@interface DLPanGestureRecognizer () + +@property (nonatomic, strong) NSNumber *isFailed; + +@end + +@implementation DLPanGestureRecognizer + +- (instancetype)init +{ + self = [super init]; + if (self) { + _direction = UISwipeGestureRecognizerDirectionDown; + _autoDetected = YES; + self.delegate = self; + } + return self; +} + +- (instancetype)initWithTarget:(id)target action:(SEL)action +{ + self = [super initWithTarget:target action:action]; + if (self) { + _direction = UISwipeGestureRecognizerDirectionDown; + _autoDetected = YES; + self.delegate = self; + } + return self; +} + +- (CGFloat)swipePercent +{ + CGFloat percent = 0; + CGPoint transition = [self translationInView:self.view]; + switch (self.direction) { + case UISwipeGestureRecognizerDirectionLeft: + percent = -transition.x / self.view.bounds.size.width; + break; + case UISwipeGestureRecognizerDirectionRight: + percent = transition.x / self.view.bounds.size.width; + break; + case UISwipeGestureRecognizerDirectionUp: + percent = -transition.y / self.view.bounds.size.height; + break; + case UISwipeGestureRecognizerDirectionDown: + default: + percent = transition.y / self.view.bounds.size.height; + break; + } + return MAX(0, MIN(1, percent)); +} + +- (void)reset +{ + [super reset]; + self.isFailed = nil; +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ + if (self.instantBegan && self.state == UIGestureRecognizerStateBegan) return; + [super touchesBegan:touches withEvent:event]; + if (self.instantBegan) self.state = UIGestureRecognizerStateBegan; +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event +{ + [super touchesMoved:touches withEvent:event]; + if (!self.scrollView || !self.scrollView.scrollEnabled) return; + + if (self.direction == UISwipeGestureRecognizerDirectionUp || self.direction == UISwipeGestureRecognizerDirectionDown) { + if (![self canScrollVertical:self.scrollView]) return; + } else { + if (![self canScrollHorizontal:self.scrollView]) return; + } + + if (self.state == UIGestureRecognizerStateFailed) return; + if (self.isFailed) { + if (self.isFailed.boolValue) { + self.state = UIGestureRecognizerStateFailed; + } + return; + } + + CGPoint velocity = [self velocityInView:self.view]; + CGPoint location = [touches.anyObject locationInView:self.view]; + CGPoint prevLocation = [touches.anyObject previousLocationInView:self.view]; + if (CGPointEqualToPoint(velocity, CGPointZero) && CGPointEqualToPoint(location, prevLocation)) return; + + BOOL isFailed = NO; + switch (self.direction) { + case UISwipeGestureRecognizerDirectionDown: { + CGFloat edgeOffset = [self contentOffsetOfEdge:UIRectEdgeTop scrollView:self.scrollView].y; + if ((fabs(velocity.x) < fabs(velocity.y)) && (location.y > prevLocation.y) && (self.scrollView.contentOffset.y <= edgeOffset)) { + isFailed = NO; + } else if (self.scrollView.contentOffset.y >= edgeOffset) { + isFailed = YES; + } + break; + } + case UISwipeGestureRecognizerDirectionUp: { + CGFloat edgeOffset = [self contentOffsetOfEdge:UIRectEdgeBottom scrollView:self.scrollView].y; + if ((fabs(velocity.x) < fabs(velocity.y)) && (location.y < prevLocation.y) && (self.scrollView.contentOffset.y >= edgeOffset)) { + isFailed = NO; + } else if (self.scrollView.contentOffset.y <= edgeOffset) { + isFailed = YES; + } + break; + } + case UISwipeGestureRecognizerDirectionRight: { + CGFloat edgeOffset = [self contentOffsetOfEdge:UIRectEdgeLeft scrollView:self.scrollView].x; + if ((fabs(velocity.y) < fabs(velocity.x)) && (location.x > prevLocation.x) && (self.scrollView.contentOffset.x <= edgeOffset)) { + isFailed = NO; + } else if (self.scrollView.contentOffset.x >= edgeOffset) { + isFailed = YES; + } + break; + } + case UISwipeGestureRecognizerDirectionLeft: { + CGFloat edgeOffset = [self contentOffsetOfEdge:UIRectEdgeRight scrollView:self.scrollView].x; + if ((fabs(velocity.y) < fabs(velocity.x)) && (location.x < prevLocation.x) && (self.scrollView.contentOffset.x >= edgeOffset)) { + isFailed = NO; + } else if (self.scrollView.contentOffset.x <= edgeOffset) { + isFailed = YES; + } + break; + } + default: + break; + } + + if (isFailed && self.shouldFailed) { + isFailed = self.shouldFailed(self); + } + + if (isFailed) { + self.state = UIGestureRecognizerStateFailed; + self.isFailed = @YES; + } else { + self.isFailed = @NO; + } +} + +#pragma mark - UIGestureRecognizerDelegate + +- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer +{ + if (self.shouldBegin) return self.shouldBegin(self); + if (self.maximumDistance <= 0) return YES; + + CGPoint location = [gestureRecognizer locationInView:gestureRecognizer.view]; + switch (self.direction) { + case UISwipeGestureRecognizerDirectionLeft: + return gestureRecognizer.view.bounds.size.width - location.x <= self.maximumDistance; + case UISwipeGestureRecognizerDirectionRight: + return location.x <= self.maximumDistance; + case UISwipeGestureRecognizerDirectionUp: + return gestureRecognizer.view.bounds.size.height - location.y <= self.maximumDistance; + case UISwipeGestureRecognizerDirectionDown: + default: + return location.y <= self.maximumDistance; + } +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer +{ + if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && + [otherGestureRecognizer.view isKindOfClass:[UIScrollView class]]) { + if (self.autoDetected) { + UIScrollView *scrollView = (UIScrollView *)otherGestureRecognizer.view; + if (self.direction == UISwipeGestureRecognizerDirectionUp || self.direction == UISwipeGestureRecognizerDirectionDown) { + if ([self canScrollHorizontal:scrollView]) return NO; + } else { + if ([self canScrollVertical:scrollView]) return NO; + } + + if (scrollView != self.scrollView) self.scrollView = scrollView; + return YES; + } else { + if (self.scrollView && self.scrollView == otherGestureRecognizer.view) { + return YES; + } + } + } + return NO; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer +{ + if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && + [otherGestureRecognizer.view isKindOfClass:[UIScrollView class]]) { + if (self.autoDetected) { + UIScrollView *scrollView = (UIScrollView *)otherGestureRecognizer.view; + if (self.direction == UISwipeGestureRecognizerDirectionUp || self.direction == UISwipeGestureRecognizerDirectionDown) { + if ([self canScrollHorizontal:scrollView]) return NO; + } else { + if ([self canScrollVertical:scrollView]) return NO; + } + + if (scrollView != self.scrollView) self.scrollView = scrollView; + return self.shouldBeRequiredToFail ? self.shouldBeRequiredToFail(otherGestureRecognizer) : YES; + } else { + if (self.scrollView && self.scrollView == otherGestureRecognizer.view) { + return self.shouldBeRequiredToFail ? self.shouldBeRequiredToFail(otherGestureRecognizer) : YES; + } + } + } + return NO; +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer +{ + if (self.shouldRequireFailure) { + return self.shouldRequireFailure(otherGestureRecognizer); + } + return NO; +} + +- (BOOL)canScrollHorizontal: (UIScrollView *)scrollView { + BOOL canHorizontal = NO; + if (scrollView.bounds.size.height > 0) { + canHorizontal = scrollView.contentSize.height + scrollView.adjustedContentInset.top + scrollView.adjustedContentInset.bottom > CGRectGetHeight(scrollView.bounds); + } + return canHorizontal; +} + +- (BOOL)canScrollVertical: (UIScrollView *)scrollView { + BOOL canVertical = NO; + if (scrollView.bounds.size.height > 0) { + canVertical = scrollView.contentSize.height + scrollView.adjustedContentInset.top + scrollView.adjustedContentInset.bottom > CGRectGetHeight(scrollView.bounds); + } + return canVertical; +} + +- (CGPoint)contentOffsetOfEdge:(UIRectEdge)edge scrollView: (UIScrollView *)scrollView { + CGPoint contentOffset = scrollView.contentOffset; + switch (edge) { + case UIRectEdgeTop: + contentOffset.y = -scrollView.adjustedContentInset.top; + break; + case UIRectEdgeLeft: + contentOffset.x = -scrollView.adjustedContentInset.left; + break; + case UIRectEdgeBottom: + contentOffset.y = scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.adjustedContentInset.bottom; + break; + case UIRectEdgeRight: + contentOffset.x = scrollView.contentSize.width - scrollView.bounds.size.width + scrollView.adjustedContentInset.right; + break; + default: + break; + } + return contentOffset; +} + +@end + +#pragma mark - FWPresentationTarget + +@interface DLPresentationTarget : NSObject + +@property (nonatomic, assign) BOOL isPopover; +@property (nonatomic, assign) BOOL shouldDismiss; + +@end + +@implementation DLPresentationTarget + +- (instancetype)init +{ + self = [super init]; + if (self) { + _shouldDismiss = YES; + } + return self; +} + +- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller +{ + return self.isPopover ? UIModalPresentationNone : controller.presentationStyle; +} + +- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController +{ + return self.shouldDismiss; +} + +- (BOOL)presentationControllerShouldDismiss:(UIPresentationController *)presentationController +{ + return self.shouldDismiss; +} + +- (void)presentationControllerDidDismiss:(UIPresentationController *)presentationController +{ + if (presentationController.presentedViewController.dl_presentationDidDismiss) { + presentationController.presentedViewController.dl_presentationDidDismiss(); + } +} + +@end + +#pragma mark - UIViewController+DLTransition + +@implementation UIViewController (DLTransition) + +- (DLAnimatedTransition *)dl_modalTransition +{ + return objc_getAssociatedObject(self, @selector(dl_modalTransition)); +} + +// 注意:App退出后台时如果弹出页面,整个present动画不会执行。如果需要设置遮罩层等,需要在viewDidAppear中处理兼容 +- (void)setDl_modalTransition:(DLAnimatedTransition *)modalTransition +{ + // 设置delegation动画,nil时清除delegate动画 + self.transitioningDelegate = modalTransition; + // 强引用,防止被自动释放,nil时释放引用 + objc_setAssociatedObject(self, @selector(dl_modalTransition), modalTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (DLAnimatedTransition *)dl_viewTransition +{ + return objc_getAssociatedObject(self, @selector(dl_viewTransition)); +} + +- (void)setDl_viewTransition:(DLAnimatedTransition *)viewTransition +{ + objc_setAssociatedObject(self, @selector(dl_viewTransition), viewTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (DLAnimatedTransition *)dl_setPresentTransition:(void (^)(DLPresentationController *))presentationBlock +{ + DLSwipeAnimatedTransition *modalTransition = [[DLSwipeAnimatedTransition alloc] init]; + modalTransition.presentationBlock = ^UIPresentationController *(UIViewController *presented, UIViewController *presenting) { + DLPresentationController *presentationController = [[DLPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting]; + if (presentationBlock) presentationBlock(presentationController); + return presentationController; + }; + self.modalPresentationStyle = UIModalPresentationCustom; + self.dl_modalTransition = modalTransition; + return modalTransition; +} + +- (DLAnimatedTransition *)dl_setAlertTransition:(void (^)(DLPresentationController *))presentationBlock +{ + DLTransformAnimatedTransition *modalTransition = [DLTransformAnimatedTransition transitionWithInTransform:CGAffineTransformMakeScale(1.1, 1.1) outTransform:CGAffineTransformIdentity]; + modalTransition.presentationBlock = ^UIPresentationController *(UIViewController *presented, UIViewController *presenting) { + DLPresentationController *presentationController = [[DLPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting]; + if (presentationBlock) presentationBlock(presentationController); + return presentationController; + }; + self.modalPresentationStyle = UIModalPresentationCustom; + self.dl_modalTransition = modalTransition; + return modalTransition; +} + +- (DLAnimatedTransition *)dl_setFadeTransition:(void (^)(DLPresentationController *))presentationBlock +{ + DLAnimatedTransition *modalTransition = [[DLAnimatedTransition alloc] init]; + modalTransition.presentationBlock = ^UIPresentationController *(UIViewController *presented, UIViewController *presenting) { + DLPresentationController *presentationController = [[DLPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting]; + if (presentationBlock) presentationBlock(presentationController); + return presentationController; + }; + self.modalPresentationStyle = UIModalPresentationCustom; + self.dl_modalTransition = modalTransition; + return modalTransition; +} + +- (void (^)(void))dl_presentationDidDismiss +{ + return objc_getAssociatedObject(self, @selector(dl_presentationDidDismiss)); +} + +- (void)setDl_presentationDidDismiss:(void (^)(void))presentationDidDismiss +{ + objc_setAssociatedObject(self, @selector(dl_presentationDidDismiss), presentationDidDismiss, OBJC_ASSOCIATION_COPY_NONATOMIC); + if (@available(iOS 13.0, *)) { + self.presentationController.delegate = [self dl_presentationTarget]; + } +} + +- (void)dl_setPopoverPresentation:(void (NS_NOESCAPE ^)(UIPopoverPresentationController *))presentationBlock shouldDismiss:(BOOL)shouldDismiss +{ + self.modalPresentationStyle = UIModalPresentationPopover; + [self dl_presentationTarget].isPopover = YES; + [self dl_presentationTarget].shouldDismiss = shouldDismiss; + self.popoverPresentationController.delegate = [self dl_presentationTarget]; + if (self.popoverPresentationController && presentationBlock) { + presentationBlock(self.popoverPresentationController); + } +} + +- (DLPresentationTarget *)dl_presentationTarget +{ + DLPresentationTarget *target = objc_getAssociatedObject(self, _cmd); + if (!target) { + target = [[DLPresentationTarget alloc] init]; + objc_setAssociatedObject(self, _cmd, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return target; +} + +@end + +#pragma mark - UIView+DLTransition + +@implementation UIView (DLTransition) + +- (UIView *)dl_transitionToController:(UIViewController *)viewController pinEdges:(BOOL)pinEdges +{ + UIView *ancestorView = [self ancestorViewWith:viewController]; + [ancestorView addSubview:self]; + if (pinEdges) { + self.translatesAutoresizingMaskIntoConstraints = NO; + NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]; + NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]; + NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]; + NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]; + NSArray *constraints = @[topConstraint, bottomConstraint, leftConstraint, rightConstraint]; + [constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *obj, NSUInteger idx, BOOL * _Nonnull stop) { + [obj setActive:YES]; + }]; + [self.superview addConstraints:constraints]; + [ancestorView setNeedsLayout]; + [ancestorView layoutIfNeeded]; + } + return ancestorView; +} + +- (UIViewController *)dl_wrappedTransitionController:(BOOL)pinEdges +{ + UIViewController *viewController = [[UIViewController alloc] init]; + [viewController.view addSubview:self]; + if (pinEdges) { + self.translatesAutoresizingMaskIntoConstraints = NO; + NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]; + NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]; + NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]; + NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]; + NSArray *constraints = @[topConstraint, bottomConstraint, leftConstraint, rightConstraint]; + [constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *obj, NSUInteger idx, BOOL * _Nonnull stop) { + [obj setActive:YES]; + }]; + [self.superview addConstraints:constraints]; + [viewController.view setNeedsLayout]; + [viewController.view layoutIfNeeded]; + } + return viewController; +} + +- (void)dl_setPresentTransition:(DLAnimatedTransitionType)transitionType + contentView:(UIView *)contentView + completion:(void (^)(BOOL))completion +{ + BOOL transitionIn = (transitionType == FWAnimatedTransitionTypePush || transitionType == FWAnimatedTransitionTypePresent); + if (transitionIn) { + self.alpha = 0; + contentView.transform = CGAffineTransformMakeTranslation(0, contentView.frame.size.height); + [UIView animateWithDuration:0.25 animations:^{ + contentView.transform = CGAffineTransformIdentity; + self.alpha = 1; + } completion:^(BOOL finished) { + if (completion) completion(finished); + }]; + } else { + [UIView animateWithDuration:0.25 animations:^{ + contentView.transform = CGAffineTransformMakeTranslation(0, contentView.frame.size.height); + self.alpha = 0; + } completion:^(BOOL finished) { + contentView.transform = CGAffineTransformIdentity; + [self removeFromSuperview]; + if (completion) completion(finished); + }]; + } +} + +- (void)dl_setAlertTransition:(DLAnimatedTransitionType)transitionType + completion:(void (^)(BOOL))completion +{ + BOOL transitionIn = (transitionType == FWAnimatedTransitionTypePush || transitionType == FWAnimatedTransitionTypePresent); + if (transitionIn) { + self.alpha = 0; + self.transform = CGAffineTransformMakeScale(1.1, 1.1); + [UIView animateWithDuration:0.25 animations:^{ + self.transform = CGAffineTransformIdentity; + self.alpha = 1; + } completion:^(BOOL finished) { + if (completion) completion(finished); + }]; + } else { + [UIView animateWithDuration:0.25 animations:^{ + self.alpha = 0; + } completion:^(BOOL finished) { + [self removeFromSuperview]; + if (completion) completion(finished); + }]; + } +} + +- (void)dl_setFadeTransition:(DLAnimatedTransitionType)transitionType + completion:(void (^)(BOOL))completion +{ + BOOL transitionIn = (transitionType == FWAnimatedTransitionTypePush || transitionType == FWAnimatedTransitionTypePresent); + if (transitionIn) { + self.alpha = 0; + [UIView animateWithDuration:0.25 animations:^{ + self.alpha = 1; + } completion:^(BOOL finished) { + if (completion) completion(finished); + }]; + } else { + [UIView animateWithDuration:0.25 animations:^{ + self.alpha = 0; + } completion:^(BOOL finished) { + [self removeFromSuperview]; + if (completion) completion(finished); + }]; + } +} + +- (UIView*)ancestorViewWith: (UIViewController *)viewController { + if (viewController.tabBarController.navigationController) { + return viewController.tabBarController.navigationController.view; + } else if (viewController.tabBarController) { + return viewController.tabBarController.view; + } else if (viewController.navigationController) { + return viewController.view; + } else { + return viewController.view; + } +} + +@end + +#pragma mark - UINavigationController+DLTransition + +@implementation UINavigationController (DLTransition) + +- (DLAnimatedTransition *)dl_navigationTransition +{ + return objc_getAssociatedObject(self, @selector(dl_navigationTransition)); +} + +- (void)setDl_navigationTransition:(DLAnimatedTransition *)navigationTransition +{ + // 设置delegate动画,nil时清理delegate动画,无需清理CA动画 + self.delegate = navigationTransition; + // 强引用,防止被自动释放,nil时释放引用 + objc_setAssociatedObject(self, @selector(dl_navigationTransition), navigationTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/QuickLocation/UIKit/ReusableView.swift b/QuickLocation/UIKit/ReusableView.swift new file mode 100644 index 00000000..1e6063f8 --- /dev/null +++ b/QuickLocation/UIKit/ReusableView.swift @@ -0,0 +1,116 @@ +// +// ReusableView.swift +// GXM-CRM +// +// Created by XUXIAOTENG on 15/12/2017. +// Copyright © 2017 GuoXiaoMei. All rights reserved. +// + +import Foundation +import UIKit + +public protocol ReusableView: AnyObject { + static var defaultReuseIdentifier: String { get } +} + +public extension ReusableView where Self: UIView { + static var defaultReuseIdentifier: String { + return NSStringFromClass(self).components(separatedBy: ".").last! + } +} + +extension UICollectionReusableView: ReusableView {} +extension UITableViewCell: ReusableView {} +extension UITableViewHeaderFooterView: ReusableView {} + +public protocol NibLoadableView: AnyObject { + static var nibName: String { get } +} + +public extension NibLoadableView where Self: UIView { + static var nibName: String { + return NSStringFromClass(self).components(separatedBy: ".").last! + } +} + +public extension UITableView { + func register(_: T.Type) { + register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) + } + + func register(_: T.Type) where T: NibLoadableView { + let bundle = Bundle(for: T.self) + let nib = UINib(nibName: T.nibName, bundle: bundle) + register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) + } + + func register(_: T.Type) { + register(T.self, forHeaderFooterViewReuseIdentifier: T.defaultReuseIdentifier) + } + + func register(_: T.Type) where T: NibLoadableView { + let bundle = Bundle(for: T.self) + let nib = UINib(nibName: T.nibName, bundle: bundle) + register(nib, forHeaderFooterViewReuseIdentifier: T.defaultReuseIdentifier) + } + + func dequeueReusableCell() -> T { + guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier) as? T else { + fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") + } + return cell + } + + func dequeueReusableHeaderFooterView() -> T { + guard let view = dequeueReusableHeaderFooterView(withIdentifier: T.defaultReuseIdentifier) as? T else { + fatalError("Could not dequeue header or footer view with identifier: \(T.defaultReuseIdentifier)") + } + return view + } + + func dequeueReusableCell(for indexPath: IndexPath) -> T { + guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else { + fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") + } + return cell + } +} + +public extension UICollectionView { + func register(_: T.Type) { + register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) + } + + func register(_: T.Type) where T: NibLoadableView { + let bundle = Bundle(for: T.self) + let nib = UINib(nibName: T.nibName, bundle: bundle) + register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) + } + + func register(_: T.Type, forSupplementaryViewOfKind kind: String) { + register(T.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: T.defaultReuseIdentifier) + } + + func register(_: T.Type, forSupplementaryViewOfKind kind: String) where T: NibLoadableView { + let bundle = Bundle(for: T.self) + let nib = UINib(nibName: T.nibName, bundle: bundle) + register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: T.defaultReuseIdentifier) + } + + func dequeueReusableCell(for indexPath: IndexPath) -> T { + guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, + for: indexPath) as? T else { + fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") + } + return cell + } + + func dequeueReusableSupplementaryView(ofKind kind: String, for indexPath: IndexPath) -> T { + guard let view = dequeueReusableSupplementaryView(ofKind: kind, + withReuseIdentifier: T.defaultReuseIdentifier, + for: indexPath) as? T else { + fatalError("Could not dequeue supplementary with identifier: \(T.defaultReuseIdentifier)") + } + return view + } +} diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView-Bridging-Header.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView-Bridging-Header.h new file mode 100644 index 00000000..df1ee9e4 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView-Bridging-Header.h @@ -0,0 +1,19 @@ +// +// TTGTagCollectionView-Bridging-Header.h +// TTGTagCollectionView +// +// Created by zekunyan on 2021/4/21. +// + +#ifndef TTGTagCollectionView_Bridging_Header_h +#define TTGTagCollectionView_Bridging_Header_h + +#import "TTGTagCollectionView.h" +#import "TTGTextTagCollectionView.h" +#import "TTGTextTag.h" +#import "TTGTextTagContent.h" +#import "TTGTextTagStringContent.h" +#import "TTGTextTagAttributedStringContent.h" +#import "TTGTextTagStyle.h" + +#endif /* TTGTagCollectionView_Bridging_Header_h */ diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView.h new file mode 100644 index 00000000..41ef2f2b --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView.h @@ -0,0 +1,112 @@ +// +// TTGTagCollectionView.h +// Pods +// +// Created by zekunyan on 15/12/26. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import + +@class TTGTagCollectionView; + +/** + * Tags scroll direction + */ +typedef NS_ENUM(NSInteger, TTGTagCollectionScrollDirection) { + TTGTagCollectionScrollDirectionVertical = 0, // Default + TTGTagCollectionScrollDirectionHorizontal = 1 +}; + +/** + * Tags alignment + */ +typedef NS_ENUM(NSInteger, TTGTagCollectionAlignment) { + TTGTagCollectionAlignmentLeft = 0, // Default + TTGTagCollectionAlignmentCenter, // Center + TTGTagCollectionAlignmentRight, // Right + TTGTagCollectionAlignmentFillByExpandingSpace, // Expand horizontal spacing and fill + TTGTagCollectionAlignmentFillByExpandingWidth, // Expand width and fill + TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine // Expand width and fill, except last line +}; + +/** + * Tags delegate + */ +@protocol TTGTagCollectionViewDelegate +@required +- (CGSize)tagCollectionView:(TTGTagCollectionView *)tagCollectionView sizeForTagAtIndex:(NSUInteger)index; + +@optional +- (BOOL)tagCollectionView:(TTGTagCollectionView *)tagCollectionView shouldSelectTag:(UIView *)tagView atIndex:(NSUInteger)index; + +- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView didSelectTag:(UIView *)tagView atIndex:(NSUInteger)index; + +- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView updateContentSize:(CGSize)contentSize; +@end + +/** + * Tags dataSource + */ +@protocol TTGTagCollectionViewDataSource +@required +- (NSUInteger)numberOfTagsInTagCollectionView:(TTGTagCollectionView *)tagCollectionView; + +- (UIView *)tagCollectionView:(TTGTagCollectionView *)tagCollectionView tagViewForIndex:(NSUInteger)index; +@end + +@interface TTGTagCollectionView : UIView +@property (nonatomic, weak) id dataSource; +@property (nonatomic, weak) id delegate; + +// Inside scrollView +@property (nonatomic, strong, readonly) UIScrollView *scrollView; + +// Tags scroll direction, default is vertical. +@property (nonatomic, assign) TTGTagCollectionScrollDirection scrollDirection; + +// Tags layout alignment, default is left. +@property (nonatomic, assign) TTGTagCollectionAlignment alignment; + +// Number of lines. 0 means no limit, default is 0 for vertical and 1 for horizontal. +@property (nonatomic, assign) NSUInteger numberOfLines; +// The real number of lines ignoring the numberOfLines value +@property (nonatomic, assign, readonly) NSUInteger actualNumberOfLines; + +// Horizontal and vertical space between tags, default is 4. +@property (nonatomic, assign) CGFloat horizontalSpacing; +@property (nonatomic, assign) CGFloat verticalSpacing; + +// Content inset, default is UIEdgeInsetsMake(2, 2, 2, 2). +@property (nonatomic, assign) UIEdgeInsets contentInset; + +// The true tags content size, readonly +@property (nonatomic, assign, readonly) CGSize contentSize; + +// Manual content height +// Default = NO, set will update content +@property (nonatomic, assign) BOOL manualCalculateHeight; +// Default = 0, set will update content +@property (nonatomic, assign) CGFloat preferredMaxLayoutWidth; + +// Scroll indicator +@property (nonatomic, assign) BOOL showsHorizontalScrollIndicator; +@property (nonatomic, assign) BOOL showsVerticalScrollIndicator; + +// Tap blank area callback +@property (nonatomic, copy) void (^onTapBlankArea)(CGPoint location); +// Tap all area callback +@property (nonatomic, copy) void (^onTapAllArea)(CGPoint location); + +/** + * Reload all tag cells + */ +- (void)reload; + +/** + * Returns the index of the tag located at the specified point. + * If item at point is not found, returns NSNotFound. + */ +- (NSInteger)indexOfTagAt:(CGPoint)point; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView.m new file mode 100644 index 00000000..fd9c6a8e --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTagCollectionView.m @@ -0,0 +1,490 @@ +// +// TTGTagCollectionView.m +// Pods +// +// Created by zekunyan on 15/12/26. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTagCollectionView.h" + +@interface TTGTagCollectionView () +@property (nonatomic, strong) UIScrollView *scrollView; +@property (nonatomic, strong) UIView *containerView; +@property (nonatomic, assign) BOOL needsLayoutTagViews; +@property (nonatomic, assign) NSUInteger actualNumberOfLines; +@end + +@implementation TTGTagCollectionView + +#pragma mark - Init + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + [self commonInit]; + } + + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)coder { + self = [super initWithCoder:coder]; + if (self) { + [self commonInit]; + } + + return self; +} + +- (void)commonInit { + if (_scrollView) { + return; + } + + _horizontalSpacing = 4; + _verticalSpacing = 4; + _contentInset = UIEdgeInsetsMake(2, 2, 2, 2); + + _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds]; + _scrollView.backgroundColor = [UIColor clearColor]; + _scrollView.userInteractionEnabled = YES; + [self addSubview:_scrollView]; + + _containerView = [[UIView alloc] initWithFrame:_scrollView.bounds]; + _containerView.backgroundColor = [UIColor clearColor]; + _containerView.userInteractionEnabled = YES; + [_scrollView addSubview:_containerView]; + + UITapGestureRecognizer *tapGesture = [UITapGestureRecognizer new]; + [tapGesture addTarget:self action:@selector(onTapGesture:)]; + [_containerView addGestureRecognizer:tapGesture]; + + [self setNeedsLayoutTagViews]; +} + +#pragma mark - Public methods + +- (void)reload { + if (![self isDelegateAndDataSourceValid]) { + return; + } + + // Remove all tag views + [_containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; + + // Add tag view + for (NSUInteger i = 0; i < [_dataSource numberOfTagsInTagCollectionView:self]; i++) { + [_containerView addSubview:[_dataSource tagCollectionView:self tagViewForIndex:i]]; + } + + // Update tag view frame + [self setNeedsLayoutTagViews]; + [self layoutTagViews]; +} + +- (NSInteger)indexOfTagAt:(CGPoint)point { + // We expect the point to be a point wrt to the TTGTagCollectionView. + // so convert this point first to a point wrt to the container view. + CGPoint convertedPoint = [self convertPoint:point toView:_containerView]; + for (NSUInteger i = 0; i < [self.dataSource numberOfTagsInTagCollectionView:self]; i++) { + UIView *tagView = [self.dataSource tagCollectionView:self tagViewForIndex:i]; + if (CGRectContainsPoint(tagView.frame, convertedPoint) && !tagView.isHidden) { + return i; + } + } + return NSNotFound; +} + +#pragma mark - Gesture + +- (void)onTapGesture:(UITapGestureRecognizer *)tapGesture { + CGPoint tapPointInCollectionView = [tapGesture locationInView:self]; + + if (![self.dataSource respondsToSelector:@selector(numberOfTagsInTagCollectionView:)] || + ![self.dataSource respondsToSelector:@selector(tagCollectionView:tagViewForIndex:)] || + ![self.delegate respondsToSelector:@selector(tagCollectionView:didSelectTag:atIndex:)]) { + if (_onTapBlankArea) { + _onTapBlankArea(tapPointInCollectionView); + } + if (_onTapAllArea) { + _onTapAllArea(tapPointInCollectionView); + } + return; + } + + CGPoint tapPointInScrollView = [tapGesture locationInView:_containerView]; + BOOL hasLocatedToTag = NO; + + for (NSUInteger i = 0; i < [self.dataSource numberOfTagsInTagCollectionView:self]; i++) { + UIView *tagView = [self.dataSource tagCollectionView:self tagViewForIndex:i]; + if (CGRectContainsPoint(tagView.frame, tapPointInScrollView) && !tagView.isHidden) { + hasLocatedToTag = YES; + if ([self.delegate respondsToSelector:@selector(tagCollectionView:shouldSelectTag:atIndex:)]) { + if ([self.delegate tagCollectionView:self shouldSelectTag:tagView atIndex:i]) { + [self.delegate tagCollectionView:self didSelectTag:tagView atIndex:i]; + } + } else { + [self.delegate tagCollectionView:self didSelectTag:tagView atIndex:i]; + } + } + } + + if (!hasLocatedToTag) { + if (_onTapBlankArea) { + _onTapBlankArea(tapPointInCollectionView); + } + } + if (_onTapAllArea) { + _onTapAllArea(tapPointInCollectionView); + } +} + +#pragma mark - Override + +- (void)layoutSubviews { + [super layoutSubviews]; + + if (!CGRectEqualToRect(_scrollView.frame, self.bounds)) { + _scrollView.frame = self.bounds; + [self setNeedsLayoutTagViews]; + [self layoutTagViews]; + _containerView.frame = (CGRect){CGPointZero, _scrollView.contentSize}; + } + [self layoutTagViews]; +} + +- (CGSize)intrinsicContentSize { + return _scrollView.contentSize; +} + +- (CGSize)sizeThatFits:(CGSize)size { + return self.contentSize; +} + +#pragma mark - Layout + +- (void)layoutTagViews { + if (!_needsLayoutTagViews || ![self isDelegateAndDataSourceValid]) { + return; + } + + if (_scrollDirection == TTGTagCollectionScrollDirectionVertical) { + [self layoutTagViewsForVerticalDirection]; + } else { + [self layoutTagViewsForHorizontalDirection]; + } + + _needsLayoutTagViews = NO; + [self invalidateIntrinsicContentSize]; +} + +- (void)layoutTagViewsForVerticalDirection { + NSUInteger count = [_dataSource numberOfTagsInTagCollectionView:self]; + NSUInteger currentLineTagsCount = 0; + CGFloat totalWidth = (_manualCalculateHeight && _preferredMaxLayoutWidth > 0) ? _preferredMaxLayoutWidth : CGRectGetWidth(self.bounds); + CGFloat maxLineWidth = totalWidth - _contentInset.left - _contentInset.right; + CGFloat currentLineX = 0; + CGFloat currentLineMaxHeight = 0; + + NSMutableArray *eachLineMaxHeightNumbers = [NSMutableArray new]; + NSMutableArray *eachLineWidthNumbers = [NSMutableArray new]; + NSMutableArray *eachLineTagCountNumbers = [NSMutableArray new]; + + NSMutableArray *> *eachLineTagIndexs = [NSMutableArray new]; + NSMutableArray *tmpTagIndexNumbers = [NSMutableArray new]; + + // Get each line max height ,width and tag count + for (NSUInteger i = 0; i < count; i++) { + CGSize tagSize = [_delegate tagCollectionView:self sizeForTagAtIndex:i]; + + if (currentLineX + tagSize.width > maxLineWidth && tmpTagIndexNumbers.count > 0) { + // New Line + [eachLineMaxHeightNumbers addObject:@(currentLineMaxHeight)]; + [eachLineWidthNumbers addObject:@(currentLineX - _horizontalSpacing)]; + [eachLineTagCountNumbers addObject:@(currentLineTagsCount)]; + [eachLineTagIndexs addObject:tmpTagIndexNumbers]; + tmpTagIndexNumbers = [NSMutableArray new]; + currentLineTagsCount = 0; + currentLineMaxHeight = 0; + currentLineX = 0; + } + + // Line limit + if (_numberOfLines != 0) { + UIView *tagView = [_dataSource tagCollectionView:self tagViewForIndex:i]; + tagView.hidden = eachLineWidthNumbers.count >= _numberOfLines; + } + + currentLineX += tagSize.width + _horizontalSpacing; + currentLineTagsCount += 1; + currentLineMaxHeight = MAX(tagSize.height, currentLineMaxHeight); + [tmpTagIndexNumbers addObject:@(i)]; + } + + // Add last + [eachLineMaxHeightNumbers addObject:@(currentLineMaxHeight)]; + [eachLineWidthNumbers addObject:@(currentLineX - _horizontalSpacing)]; + [eachLineTagCountNumbers addObject:@(currentLineTagsCount)]; + [eachLineTagIndexs addObject:tmpTagIndexNumbers]; + + // Actual number of lines + _actualNumberOfLines = eachLineTagCountNumbers.count; + + // Line limit + if (_numberOfLines != 0) { + eachLineMaxHeightNumbers = [[eachLineMaxHeightNumbers subarrayWithRange:NSMakeRange(0, MIN(eachLineMaxHeightNumbers.count, _numberOfLines))] mutableCopy]; + eachLineWidthNumbers = [[eachLineWidthNumbers subarrayWithRange:NSMakeRange(0, MIN(eachLineWidthNumbers.count, _numberOfLines))] mutableCopy]; + eachLineTagCountNumbers = [[eachLineTagCountNumbers subarrayWithRange:NSMakeRange(0, MIN(eachLineTagCountNumbers.count, _numberOfLines))] mutableCopy]; + eachLineTagIndexs = [[eachLineTagIndexs subarrayWithRange:NSMakeRange(0, MIN(eachLineTagIndexs.count, _numberOfLines))] mutableCopy]; + } + + // Prepare + [self layoutEachLineTagsWithMaxLineWidth:maxLineWidth + numberOfLines:eachLineTagCountNumbers.count + eachLineTagIndexs:eachLineTagIndexs + eachLineTagCount:eachLineTagCountNumbers + eachLineWidth:eachLineWidthNumbers + eachLineMaxHeight:eachLineMaxHeightNumbers]; +} + +- (void)layoutTagViewsForHorizontalDirection { + NSInteger count = [_dataSource numberOfTagsInTagCollectionView:self]; + _numberOfLines = _numberOfLines == 0 ? 1 : _numberOfLines; + + CGFloat maxLineWidth = 0; + + NSMutableArray *eachLineMaxHeightNumbers = [NSMutableArray new]; + NSMutableArray *eachLineWidthNumbers = [NSMutableArray new]; + NSMutableArray *eachLineTagCountNumbers = [NSMutableArray new]; + + NSMutableArray *> *eachLineTagIndexs = [NSMutableArray new]; + + // Init each line + for (NSInteger currentLine = 0; currentLine < _numberOfLines; currentLine++) { + [eachLineMaxHeightNumbers addObject:@0]; + [eachLineWidthNumbers addObject:@0]; + [eachLineTagCountNumbers addObject:@0]; + [eachLineTagIndexs addObject:[NSMutableArray new]]; + } + + // Add tags + for (NSUInteger tagIndex = 0; tagIndex < count; tagIndex++) { + NSUInteger currentLine = tagIndex % _numberOfLines; + + NSUInteger currentLineTagsCount = eachLineTagCountNumbers[currentLine].unsignedIntegerValue; + CGFloat currentLineMaxHeight = eachLineMaxHeightNumbers[currentLine].floatValue; + CGFloat currentLineX = eachLineWidthNumbers[currentLine].floatValue; + NSMutableArray *currentLineTagIndexNumbers = eachLineTagIndexs[currentLine]; + + CGSize tagSize = [_delegate tagCollectionView:self sizeForTagAtIndex:tagIndex]; + currentLineX += tagSize.width + _horizontalSpacing; + currentLineMaxHeight = MAX(tagSize.height, currentLineMaxHeight); + currentLineTagsCount += 1; + [currentLineTagIndexNumbers addObject:@(tagIndex)]; + + eachLineTagCountNumbers[currentLine] = @(currentLineTagsCount); + eachLineMaxHeightNumbers[currentLine] = @(currentLineMaxHeight); + eachLineWidthNumbers[currentLine] = @(currentLineX); + eachLineTagIndexs[currentLine] = currentLineTagIndexNumbers; + } + + // Remove extra space + for (NSInteger currentLine = 0; currentLine < _numberOfLines; currentLine++) { + CGFloat currentLineWidth = eachLineWidthNumbers[currentLine].floatValue; + currentLineWidth -= _horizontalSpacing; + eachLineWidthNumbers[currentLine] = @(currentLineWidth); + + maxLineWidth = MAX(currentLineWidth, maxLineWidth); + } + + // Prepare + [self layoutEachLineTagsWithMaxLineWidth:maxLineWidth + numberOfLines:eachLineTagCountNumbers.count + eachLineTagIndexs:eachLineTagIndexs + eachLineTagCount:eachLineTagCountNumbers + eachLineWidth:eachLineWidthNumbers + eachLineMaxHeight:eachLineMaxHeightNumbers]; +} + +- (void)layoutEachLineTagsWithMaxLineWidth:(CGFloat)maxLineWidth + numberOfLines:(NSUInteger)numberOfLines + eachLineTagIndexs:(NSArray *> *)eachLineTagIndexs + eachLineTagCount:(NSArray *)eachLineTagCount + eachLineWidth:(NSArray *)eachLineWidth + eachLineMaxHeight:(NSArray *)eachLineMaxHeight { + + CGFloat currentYBase = _contentInset.top; + + for (NSUInteger currentLine = 0; currentLine < numberOfLines; currentLine++) { + CGFloat currentLineMaxHeight = eachLineMaxHeight[currentLine].floatValue; + CGFloat currentLineWidth = eachLineWidth[currentLine].floatValue; + CGFloat currentLineTagsCount = eachLineTagCount[currentLine].unsignedIntegerValue; + + // Alignment x offset + CGFloat currentLineXOffset = 0; + CGFloat currentLineAdditionWidth = 0; + CGFloat acturalHorizontalSpacing = _horizontalSpacing; + __block CGFloat currentLineX = 0; + + switch (_alignment) { + case TTGTagCollectionAlignmentLeft: + currentLineXOffset = _contentInset.left; + break; + case TTGTagCollectionAlignmentCenter: + currentLineXOffset = (maxLineWidth - currentLineWidth) / 2 + _contentInset.left; + break; + case TTGTagCollectionAlignmentRight: + currentLineXOffset = maxLineWidth - currentLineWidth + _contentInset.left; + break; + case TTGTagCollectionAlignmentFillByExpandingSpace: + currentLineXOffset = _contentInset.left; + acturalHorizontalSpacing = _horizontalSpacing + + (maxLineWidth - currentLineWidth) / (CGFloat)(currentLineTagsCount - 1); + currentLineWidth = maxLineWidth; + break; + case TTGTagCollectionAlignmentFillByExpandingWidth: + case TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine: + currentLineXOffset = _contentInset.left; + currentLineAdditionWidth = (maxLineWidth - currentLineWidth) / (CGFloat)currentLineTagsCount; + currentLineWidth = maxLineWidth; + + if (_alignment == TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine && + currentLine == numberOfLines - 1 && + numberOfLines != 1) { + // Reset last line width for TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine + currentLineAdditionWidth = 0; + } + + break; + } + + // Current line + [eachLineTagIndexs[currentLine] enumerateObjectsUsingBlock:^(NSNumber * _Nonnull tagIndexNumber, NSUInteger idx, BOOL * _Nonnull stop) { + NSUInteger tagIndex = tagIndexNumber.unsignedIntegerValue; + + UIView *tagView = [self.dataSource tagCollectionView:self tagViewForIndex:tagIndex]; + CGSize tagSize = [self.delegate tagCollectionView:self sizeForTagAtIndex:tagIndex]; + + CGPoint origin; + origin.x = currentLineXOffset + currentLineX; + origin.y = currentYBase + (currentLineMaxHeight - tagSize.height) / 2; + + tagSize.width += currentLineAdditionWidth; + if (self.scrollDirection == TTGTagCollectionScrollDirectionVertical && tagSize.width > maxLineWidth) { + tagSize.width = maxLineWidth; + } + + tagView.hidden = NO; + tagView.frame = (CGRect){origin, tagSize}; + + currentLineX += tagSize.width + acturalHorizontalSpacing; + }]; + + // Next line + currentYBase += currentLineMaxHeight + _verticalSpacing; + } + + // Content size + maxLineWidth += _contentInset.right + _contentInset.left; + CGSize contentSize = CGSizeMake(maxLineWidth, currentYBase - _verticalSpacing + _contentInset.bottom); + if (!CGSizeEqualToSize(contentSize, _scrollView.contentSize)) { + _scrollView.contentSize = contentSize; + _containerView.frame = (CGRect){CGPointZero, contentSize}; + + if ([self.delegate respondsToSelector:@selector(tagCollectionView:updateContentSize:)]) { + [self.delegate tagCollectionView:self updateContentSize:contentSize]; + } + } +} + +- (void)setNeedsLayoutTagViews { + _needsLayoutTagViews = YES; +} + +#pragma mark - Check delegate and dataSource + +- (BOOL)isDelegateAndDataSourceValid { + BOOL isValid = _delegate != nil && _dataSource != nil; + isValid = isValid && [_delegate respondsToSelector:@selector(tagCollectionView:sizeForTagAtIndex:)]; + isValid = isValid && [_dataSource respondsToSelector:@selector(tagCollectionView:tagViewForIndex:)]; + isValid = isValid && [_dataSource respondsToSelector:@selector(numberOfTagsInTagCollectionView:)]; + return isValid; +} + +#pragma mark - Setter Getter + +- (UIScrollView *)scrollView { + return _scrollView; +} + +- (void)setScrollDirection:(TTGTagCollectionScrollDirection)scrollDirection { + _scrollDirection = scrollDirection; + [self setNeedsLayoutTagViews]; +} + +- (void)setAlignment:(TTGTagCollectionAlignment)alignment { + _alignment = alignment; + [self setNeedsLayoutTagViews]; +} + +- (void)setNumberOfLines:(NSUInteger)numberOfLines { + _numberOfLines = numberOfLines; + [self setNeedsLayoutTagViews]; +} + +- (NSUInteger)actualNumberOfLines { + if (_scrollDirection == TTGTagCollectionScrollDirectionHorizontal) { + return _numberOfLines; + } else { + return _actualNumberOfLines; + } +} + +- (void)setHorizontalSpacing:(CGFloat)horizontalSpacing { + _horizontalSpacing = horizontalSpacing; + [self setNeedsLayoutTagViews]; +} + +- (void)setVerticalSpacing:(CGFloat)verticalSpacing { + _verticalSpacing = verticalSpacing; + [self setNeedsLayoutTagViews]; +} + +- (void)setContentInset:(UIEdgeInsets)contentInset { + _contentInset = contentInset; + [self setNeedsLayoutTagViews]; +} + +- (CGSize)contentSize { + [self layoutTagViews]; + return _scrollView.contentSize; +} + +- (void)setManualCalculateHeight:(BOOL)manualCalculateHeight { + _manualCalculateHeight = manualCalculateHeight; + [self setNeedsLayoutTagViews]; +} + +- (void)setPreferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth { + _preferredMaxLayoutWidth = preferredMaxLayoutWidth; + [self setNeedsLayoutTagViews]; +} + +- (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator { + _scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator; +} + +- (BOOL)showsHorizontalScrollIndicator { + return _scrollView.showsHorizontalScrollIndicator; +} + +- (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator { + _scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator; +} + +- (BOOL)showsVerticalScrollIndicator { + return _scrollView.showsVerticalScrollIndicator; +} + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTag.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTag.h new file mode 100644 index 00000000..9f791f4c --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTag.h @@ -0,0 +1,106 @@ +// +// TTGTextTag.h +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import +#import + +#import "TTGTextTagStyle.h" +#import "TTGTextTagContent.h" + +@interface TTGTextTag : NSObject + +/// ID +@property (nonatomic, assign, readonly) NSUInteger tagId; // Auto increase. The only identifier and main key for a tag + +/// Attachment object. You can use this to bind any object you want to each tag. +@property (nonatomic, strong) id _Nullable attachment; + +/// Normal state content and style +@property (nonatomic, copy) TTGTextTagContent * _Nonnull content; +@property (nonatomic, copy) TTGTextTagStyle * _Nonnull style; + +/// Selected state content and style +@property (nonatomic, copy) TTGTextTagContent * _Nullable selectedContent; +@property (nonatomic, copy) TTGTextTagStyle * _Nullable selectedStyle; + +/// Selection state +@property (nonatomic, assign) BOOL selected; + +/// Init + +/** + Init with single content and style + + @param content content for both normal and selection state. + @param style style for both normal and selection state. + @return instance + */ +- (instancetype _Nonnull)initWithContent:(TTGTextTagContent *_Nonnull)content + style:(TTGTextTagStyle *_Nonnull)style; + +/** + Init with different content and style + + @param content content for normal state + @param style style for normal state + @param selectedContent content for selection state + @param selectedStyle style for selection state + @return instance + */ +- (instancetype _Nonnull)initWithContent:(TTGTextTagContent *_Nonnull)content + style:(TTGTextTagStyle *_Nonnull)style + selectedContent:(TTGTextTagContent *_Nullable)selectedContent + selectedStyle:(TTGTextTagStyle *_Nullable)selectedStyle; + +/** + Tag with single content and style + + @param content content for both normal and selection state. + @param style style for both normal and selection state. + @return instance + */ ++ (instancetype _Nonnull)tagWithContent:(TTGTextTagContent *_Nonnull)content + style:(TTGTextTagStyle *_Nonnull)style; + +/** + Tag with different content and style + + @param content content for normal state + @param style style for normal state + @param selectedContent content for selection state + @param selectedStyle style for selection state + @return instance + */ ++ (instancetype _Nonnull)tagWithContent:(TTGTextTagContent *_Nonnull)content + style:(TTGTextTagStyle *_Nonnull)style + selectedContent:(TTGTextTagContent *_Nullable)selectedContent + selectedStyle:(TTGTextTagStyle *_Nullable)selectedStyle; + +/** + Get current state rightful content + + @return content + */ +- (TTGTextTagContent *_Nonnull)getRightfulContent; + +/** + Get current state rightful style + + @return style + */ +- (TTGTextTagStyle *_Nonnull)getRightfulStyle; + +/// Base system methods +- (BOOL)isEqual:(id _Nullable)other; +- (BOOL)isEqualToTag:(TTGTextTag *_Nullable)tag; +- (NSUInteger)hash; + +/// Copy +- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTag.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTag.m new file mode 100644 index 00000000..a9e008dc --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTag.m @@ -0,0 +1,123 @@ +// +// TTGTextTag.m +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTag.h" +#import "TTGTextTagStringContent.h" + +static NSUInteger TTGTextTagAutoIncreasedId = 0; + +@implementation TTGTextTag + +- (instancetype)initWithContent:(TTGTextTagContent *)content + style:(TTGTextTagStyle *)style { + self = [self init]; + if (self) { + self.content = content; + self.style = style; + } + return self; +} + +- (instancetype)initWithContent:(TTGTextTagContent *)content + style:(TTGTextTagStyle *)style + selectedContent:(TTGTextTagContent *)selectedContent + selectedStyle:(TTGTextTagStyle *)selectedStyle { + self = [self init]; + if (self) { + self.content = content; + self.style = style; + self.selectedContent = selectedContent; + self.selectedStyle = selectedStyle; + } + return self; +} + ++ (instancetype)tagWithContent:(TTGTextTagContent *)content + style:(TTGTextTagStyle *)style { + return [[self alloc] initWithContent:content style:style]; +} + ++ (instancetype)tagWithContent:(TTGTextTagContent *)content + style:(TTGTextTagStyle *)style + selectedContent:(TTGTextTagContent *)selectedContent + selectedStyle:(TTGTextTagStyle *)selectedStyle { + return [[self alloc] initWithContent:content + style:style + selectedContent:selectedContent + selectedStyle:selectedStyle]; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _tagId = TTGTextTagAutoIncreasedId++; + _attachment = nil; + } + return self; +} + +- (TTGTextTagContent *)selectedContent { + if (_selectedContent == nil) { + _selectedContent = [_content copy]; + } + return _selectedContent; +} + +- (TTGTextTagStyle *)selectedStyle { + if (_selectedStyle == nil) { + _selectedStyle = [_style copy]; + } + return _selectedStyle; +} + +- (TTGTextTagContent *)getRightfulContent { + return _selected ? self.selectedContent : self.content; +} + +- (TTGTextTagStyle *)getRightfulStyle { + return _selected ? self.selectedStyle : self.style; +} + +- (BOOL)isEqual:(id)other { + if (other == self) + return YES; + if (!other || ![[other class] isEqual:[self class]]) + return NO; + + return [self isEqualToTag:other]; +} + +- (BOOL)isEqualToTag:(TTGTextTag *)tag { + if (self == tag) + return YES; + if (tag == nil) + return NO; + if (self.tagId != tag.tagId) + return NO; + return YES; +} + +- (NSUInteger)hash { + return (NSUInteger)self.tagId; +} + +- (id)copyWithZone:(nullable NSZone *)zone { + TTGTextTag *copy = (TTGTextTag *)[[[self class] allocWithZone:zone] init]; + if (copy != nil) { + copy->_tagId = TTGTextTagAutoIncreasedId++; + copy.attachment = self.attachment; + copy.content = self.content; + copy.style = self.style; + copy.selected = self.selected; + copy.selectedContent = self.selectedContent; + copy.selectedStyle = self.selectedStyle; + } + return copy; +} + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagAttributedStringContent.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagAttributedStringContent.h new file mode 100644 index 00000000..1d62aae4 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagAttributedStringContent.h @@ -0,0 +1,29 @@ +// +// TTGTextTagAttributedStringContent.h +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagContent.h" + +/** + Rich text content for tag + */ +@interface TTGTextTagAttributedStringContent : TTGTextTagContent + +/// Attributed text +@property (nonatomic, copy) NSAttributedString * _Nonnull attributedText; + +/// Init with rich text +- (instancetype _Nonnull)initWithAttributedText:(NSAttributedString *_Nonnull)attributedText; + +/// Content with rich text ++ (instancetype _Nonnull)contentWithAttributedText:(NSAttributedString *_Nonnull)attributedText; + +/// Base system methods +- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone; +- (NSString *_Nonnull)description; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagAttributedStringContent.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagAttributedStringContent.m new file mode 100644 index 00000000..3a46e3e6 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagAttributedStringContent.m @@ -0,0 +1,48 @@ +// +// TTGTextTagAttributedStringContent.m +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagAttributedStringContent.h" + +@implementation TTGTextTagAttributedStringContent + +- (instancetype)initWithAttributedText:(NSAttributedString *)attributedText { + self = [super init]; + if (self) { + self.attributedText = attributedText; + } + return self; +} + ++ (instancetype)contentWithAttributedText:(NSAttributedString *)attributedText { + return [[self alloc] initWithAttributedText:attributedText]; +} + +- (NSAttributedString *)getContentAttributedString { + return self.attributedText; +} + +- (NSAttributedString *)attributedText { + return _attributedText ?: [NSAttributedString new]; +} + +- (id)copyWithZone:(NSZone *)zone { + TTGTextTagAttributedStringContent *copy = (TTGTextTagAttributedStringContent *)[super copyWithZone:zone]; + if (copy != nil) { + copy.attributedText = self.attributedText; + } + return copy; +} + +- (NSString *)description { + NSMutableString *description = [NSMutableString stringWithFormat:@"<%@: ", NSStringFromClass([self class])]; + [description appendFormat:@"self.attributedText=%@", self.attributedText]; + [description appendString:@">"]; + return description; +} + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagCollectionView.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagCollectionView.h new file mode 100644 index 00000000..bfe6af05 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagCollectionView.h @@ -0,0 +1,124 @@ +// +// TTGTextTagCollectionView.h +// Pods +// +// Created by zekunyan on 15/12/26. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import + +#import "TTGTagCollectionView.h" +#import "TTGTextTag.h" +#import "TTGTextTagStringContent.h" +#import "TTGTextTagAttributedStringContent.h" + +/** + Highly useful for text tag display. + */ + +@class TTGTextTagCollectionView; + +/// Delegate +@protocol TTGTextTagCollectionViewDelegate +@optional + +- (BOOL)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView + canTapTag:(TTGTextTag *)tag + atIndex:(NSUInteger)index; + +- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView + didTapTag:(TTGTextTag *)tag + atIndex:(NSUInteger)index; + +- (void)textTagCollectionView:(TTGTextTagCollectionView *)textTagCollectionView + updateContentSize:(CGSize)contentSize; +@end + +/// Main Class +@interface TTGTextTagCollectionView : UIView +/// Delegate +@property (weak, nonatomic) id delegate; + +/// Inside scrollView +@property (nonatomic, strong, readonly) UIScrollView *scrollView; + +/// Define if the tag can be selected. +@property (assign, nonatomic) BOOL enableTagSelection; + +/// Tags scroll direction, default is vertical. +@property (nonatomic, assign) TTGTagCollectionScrollDirection scrollDirection; + +/// Tags layout alignment, default is left. +@property (nonatomic, assign) TTGTagCollectionAlignment alignment; + +/// Number of lines. 0 means no limit, default is 0 for vertical and 1 for horizontal. +@property (nonatomic, assign) NSUInteger numberOfLines; +/// The real number of lines ignoring the numberOfLines value +@property (nonatomic, assign, readonly) NSUInteger actualNumberOfLines; + +/// Tag selection limit, default is 0, means no limit +@property (nonatomic, assign) NSUInteger selectionLimit; + +/// Horizontal and vertical space between tags, default is 4. +@property (assign, nonatomic) CGFloat horizontalSpacing; +@property (assign, nonatomic) CGFloat verticalSpacing; + +/// Content inset, like padding, default is UIEdgeInsetsMake(2, 2, 2, 2). +@property (nonatomic, assign) UIEdgeInsets contentInset; + +/// The true tags content size, readonly +@property (nonatomic, assign, readonly) CGSize contentSize; + +/// Manual content height +/// Default = NO, set will update content +@property (nonatomic, assign) BOOL manualCalculateHeight; +/// Default = 0, set will update content +@property (nonatomic, assign) CGFloat preferredMaxLayoutWidth; + +/// Scroll indicator +@property (nonatomic, assign) BOOL showsHorizontalScrollIndicator; +@property (nonatomic, assign) BOOL showsVerticalScrollIndicator; + +/// Tap blank area callback +@property (nonatomic, copy) void (^onTapBlankArea)(CGPoint location); +/// Tap all area callback +@property (nonatomic, copy) void (^onTapAllArea)(CGPoint location); + +/// Reload +- (void)reload; + +/// Add +- (void)addTag:(TTGTextTag *)tag; +- (void)addTags:(NSArray *)tags; + +/// Insert +- (void)insertTag:(TTGTextTag *)tag atIndex:(NSUInteger)index; +- (void)insertTags:(NSArray *)tags atIndex:(NSUInteger)index; + +/// Update +- (void)updateTagAtIndex:(NSUInteger)index selected:(BOOL)selected; +- (void)updateTagAtIndex:(NSUInteger)index withNewTag:(TTGTextTag *)tag; + +/// Remove +- (void)removeTag:(TTGTextTag *)tag; +- (void)removeTagById:(NSUInteger)tagId; +- (void)removeTagAtIndex:(NSUInteger)index; +- (void)removeAllTags; + +/// Get tag +- (TTGTextTag *)getTagAtIndex:(NSUInteger)index; +- (NSArray *)getTagsInRange:(NSRange)range; + +/// Get all +- (NSArray *)allTags; +- (NSArray *)allSelectedTags; +- (NSArray *)allNotSelectedTags; + +/** + * Returns the index of the tag located at the specified point. + * If item at point is not found, returns NSNotFound. + */ +- (NSInteger)indexOfTagAtPoint:(CGPoint)point; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagCollectionView.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagCollectionView.m new file mode 100644 index 00000000..b1ef6a2a --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagCollectionView.m @@ -0,0 +1,639 @@ +// +// TTGTextTagCollectionView.m +// Pods +// +// Created by zekunyan on 15/12/26. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagCollectionView.h" + +#pragma mark - TTGTextTagGradientLabel + +@interface TTGTextTagGradientLabel : UILabel +@end + +@implementation TTGTextTagGradientLabel ++ (Class)layerClass { + return [CAGradientLayer class]; +} +@end + +#pragma mark - TTGTextTagLabel + +@interface TTGTextTagComponentView : UIView +@property (nonatomic, strong) TTGTextTag *config; +@property (nonatomic, strong) TTGTextTagGradientLabel *label; +@property (nonatomic, strong) CAShapeLayer *borderLayer; + +- (BOOL)isEqual:(id)other; + +- (BOOL)isEqualToComponentView:(TTGTextTagComponentView *)label; + +- (NSUInteger)hash; +@end + +@implementation TTGTextTagComponentView + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + [self commonInit]; + } + return self; +} + +- (void)commonInit { + _label = [[TTGTextTagGradientLabel alloc] initWithFrame:self.bounds]; + _label.textAlignment = NSTextAlignmentCenter; + _label.userInteractionEnabled = YES; + [self addSubview:_label]; +} + +#pragma mark - Layout + +- (void)layoutSubviews { + [super layoutSubviews]; + + // Update frame + _label.frame = self.bounds; + + // Get new path + UIBezierPath *path = [self getNewPath]; + // Mask + [self updateMaskWithPath:path]; + // Border + [self updateBorderWithPath:path]; + // Shadow + [self updateShadowWithPath:path]; +} + +#pragma mark - intrinsicContentSize + +- (CGSize)intrinsicContentSize { + return _label.intrinsicContentSize; +} + +#pragma mark - Apply config + +- (void)updateContent { + // Content + _label.attributedText = _config.getRightfulContent.getContentAttributedString; +} + +- (void)updateContentStyle { + // Normal background + _label.backgroundColor = _config.getRightfulStyle.backgroundColor; + + // Text alignment + _label.textAlignment = _config.getRightfulStyle.textAlignment; + + // Gradient background + if (_config.getRightfulStyle.enableGradientBackground) { + _label.backgroundColor = [UIColor clearColor]; + ((CAGradientLayer *)_label.layer).colors = @[(id)_config.getRightfulStyle.gradientBackgroundStartColor.CGColor, + (id)_config.getRightfulStyle.gradientBackgroundEndColor.CGColor]; + ((CAGradientLayer *)_label.layer).startPoint = _config.getRightfulStyle.gradientBackgroundStartPoint; + ((CAGradientLayer *)_label.layer).endPoint = _config.getRightfulStyle.gradientBackgroundEndPoint; + } +} + +- (void)updateFrameWithMaxSize:(CGSize)maxSize { + [_label sizeToFit]; + + CGSize finalSize = _label.frame.size; + + finalSize.width += _config.getRightfulStyle.extraSpace.width; + finalSize.height += _config.getRightfulStyle.extraSpace.height; + + if (_config.getRightfulStyle.maxWidth > 0 && finalSize.width > _config.getRightfulStyle.maxWidth) { + finalSize.width = _config.getRightfulStyle.maxWidth; + } + if (_config.getRightfulStyle.minWidth > 0 && finalSize.width < _config.getRightfulStyle.minWidth) { + finalSize.width = _config.getRightfulStyle.minWidth; + } + if (_config.getRightfulStyle.exactWidth > 0) { + finalSize.width = _config.getRightfulStyle.exactWidth; + } + if (_config.getRightfulStyle.exactHeight > 0) { + finalSize.height = _config.getRightfulStyle.exactHeight; + } + + if (maxSize.width > 0) { + finalSize.width = MIN(maxSize.width, finalSize.width); + } + if (maxSize.height > 0) { + finalSize.height = MIN(maxSize.height, finalSize.height); + } + + CGRect frame = self.frame; + frame.size = finalSize; + self.frame = frame; + _label.frame = self.bounds; +} + +- (void)updateShadowWithPath:(UIBezierPath *)path { + self.layer.shadowColor = _config.getRightfulStyle.shadowColor.CGColor; + self.layer.shadowOffset = _config.getRightfulStyle.shadowOffset; + self.layer.shadowRadius = _config.getRightfulStyle.shadowRadius; + self.layer.shadowOpacity = (float)_config.getRightfulStyle.shadowOpacity; + self.layer.shadowPath = path.CGPath; + self.layer.shouldRasterize = YES; + [self.layer setRasterizationScale:[[UIScreen mainScreen] scale]]; +} + +- (void)updateMaskWithPath:(UIBezierPath *)path { + CAShapeLayer *maskLayer = [CAShapeLayer layer]; + maskLayer.frame = self.bounds; + maskLayer.path = path.CGPath; + _label.layer.mask = maskLayer; +} + +- (void)updateBorderWithPath:(UIBezierPath *)path { + if (!_borderLayer) { + _borderLayer = [CAShapeLayer new]; + } + [_borderLayer removeFromSuperlayer]; + _borderLayer.frame = self.bounds; + _borderLayer.path = path.CGPath; + _borderLayer.fillColor = nil; + _borderLayer.opacity = 1; + _borderLayer.lineWidth = _config.getRightfulStyle.borderWidth; + _borderLayer.strokeColor = _config.getRightfulStyle.borderColor.CGColor; + _borderLayer.lineCap = kCALineCapRound; + _borderLayer.lineJoin = kCALineJoinRound; + [self.layer addSublayer:_borderLayer]; +} + +- (UIBezierPath *)getNewPath { + // Round corner + UIRectCorner corners = (UIRectCorner)-1; + if (_config.getRightfulStyle.cornerTopLeft) { + corners = UIRectCornerTopLeft; + } + if (_config.getRightfulStyle.cornerTopRight) { + if (corners == -1) { + corners = UIRectCornerTopRight; + } else { + corners = corners | UIRectCornerTopRight; + } + } + if (_config.getRightfulStyle.cornerBottomLeft) { + if (corners == -1) { + corners = UIRectCornerBottomLeft; + } else { + corners = corners | UIRectCornerBottomLeft; + } + } + if (_config.getRightfulStyle.cornerBottomRight) { + if (corners == -1) { + corners = UIRectCornerBottomRight; + } else { + corners = corners | UIRectCornerBottomRight; + } + } + + // Corner radius + CGFloat currentCornerRadius = _config.getRightfulStyle.cornerRadius; + + // Path + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds + byRoundingCorners:corners + cornerRadii:CGSizeMake(currentCornerRadius, currentCornerRadius)]; + return path; +} + +#pragma mark - Base + +- (BOOL)isEqual:(id)other { + if (other == self) + return YES; + if (!other || ![[other class] isEqual:[self class]]) + return NO; + return [self isEqualToComponentView:other]; +} + +- (BOOL)isEqualToComponentView:(TTGTextTagComponentView *)label { + if (self == label) + return YES; + if (label == nil) + return NO; + if (self.config != label.config && ![self.config isEqualToTag:label.config]) + return NO; + return YES; +} + +- (NSUInteger)hash { + return [self.config hash]; +} + +@end + +#pragma mark - TTGTextTagCollectionView + +@interface TTGTextTagCollectionView () +@property (strong, atomic) NSMutableArray *tagLabels; +@property (strong, nonatomic) TTGTagCollectionView *tagCollectionView; +@end + +@implementation TTGTextTagCollectionView + +#pragma mark - Init + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)coder { + self = [super initWithCoder:coder]; + if (self) { + [self commonInit]; + } + return self; +} + +- (void)commonInit { + if (_tagCollectionView) { + return; + } + + _enableTagSelection = YES; + _tagLabels = [NSMutableArray new]; + + _tagCollectionView = [[TTGTagCollectionView alloc] initWithFrame:self.bounds]; + _tagCollectionView.delegate = self; + _tagCollectionView.dataSource = self; + _tagCollectionView.horizontalSpacing = 8; + _tagCollectionView.verticalSpacing = 8; + [self addSubview:_tagCollectionView]; +} + +#pragma mark - Override + +- (CGSize)intrinsicContentSize { + return [_tagCollectionView intrinsicContentSize]; +} + +- (void)layoutSubviews { + [super layoutSubviews]; + if (!CGRectEqualToRect(_tagCollectionView.frame, self.bounds)) { + [self updateAllLabelStyleAndFrame]; + _tagCollectionView.frame = self.bounds; + [_tagCollectionView setNeedsLayout]; + [_tagCollectionView layoutIfNeeded]; + [self invalidateIntrinsicContentSize]; + } +} + +- (CGSize)sizeThatFits:(CGSize)size { + return self.contentSize; +} + +#pragma mark - Public methods + +- (void)reload { + [self updateAllLabelStyleAndFrame]; + [_tagCollectionView reload]; + [self invalidateIntrinsicContentSize]; +} + +- (void)addTag:(TTGTextTag *)tag { + [self insertTag:tag atIndex:_tagLabels.count]; +} + +- (void)addTags:(NSArray *)tags { + [self insertTags:tags atIndex:_tagLabels.count]; +} + +- (void)insertTag:(TTGTextTag *)tag atIndex:(NSUInteger)index { + if ([tag isKindOfClass:[TTGTextTag class]]) { + [self insertTags:@[tag] atIndex:index]; + } +} + +- (void)insertTags:(NSArray *)tags atIndex:(NSUInteger)index { + if (![tags isKindOfClass:[NSArray class]] || index > _tagLabels.count || tags.count == 0) { + return; + } + + NSMutableArray *newTagLabels = [NSMutableArray new]; + for (TTGTextTag *tag in tags) { + if ([tag isKindOfClass:[TTGTextTag class]]) { + TTGTextTagComponentView *label = [self newLabelWithConfig:tag]; + [newTagLabels addObject:label]; + } + } + [_tagLabels insertObjects:newTagLabels atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index, newTagLabels.count)]]; +} + +- (void)removeTag:(TTGTextTag *)tag { + if ([tag isKindOfClass:[TTGTextTag class]]) { + [self removeTagById:tag.tagId]; + } +} + +- (void)removeTagById:(NSUInteger)tagId { + TTGTextTagComponentView *labelToRemove = nil; + for (TTGTextTagComponentView *label in _tagLabels) { + if (label.config.tagId == tagId) { + labelToRemove = label; + } + } + if (labelToRemove) { + [_tagLabels removeObject:labelToRemove]; + } +} + +- (void)removeTagAtIndex:(NSUInteger)index { + if (index >= _tagLabels.count) { + return; + } + [_tagLabels removeObjectAtIndex:index]; +} + +- (void)removeAllTags { + [_tagLabels removeAllObjects]; +} + +- (void)updateTagAtIndex:(NSUInteger)index selected:(BOOL)selected { + TTGTextTag *tag = [self getTagAtIndex:index]; + tag.selected = selected; +} + +- (void)updateTagAtIndex:(NSUInteger)index withNewTag:(TTGTextTag *)tag { + if (index < _tagLabels.count && [tag isKindOfClass:[TTGTextTag class]]) { + TTGTextTagComponentView *label = _tagLabels[index]; + label.config = tag; + [label updateContent]; + } +} + +- (TTGTextTag *)getTagAtIndex:(NSUInteger)index { + if (index < _tagLabels.count) { + return _tagLabels[index].config; + } else { + return nil; + } +} + +- (NSArray *)getTagsInRange:(NSRange)range { + if (NSMaxRange(range) <= _tagLabels.count) { + NSMutableArray *tags = [NSMutableArray new]; + for (TTGTextTagComponentView *label in [_tagLabels subarrayWithRange:range]) { + if (label.config) { + [tags addObject:label.config]; + } + } + return [tags copy]; + } else { + return nil; + } +} + +- (NSArray *)allTags { + NSMutableArray *allTags = [NSMutableArray new]; + + for (TTGTextTagComponentView *label in _tagLabels) { + if (label.config) { + [allTags addObject:label.config]; + } + } + + return [allTags copy]; +} + +- (NSArray *)allSelectedTags { + NSMutableArray *allTags = [NSMutableArray new]; + + for (TTGTextTagComponentView *label in _tagLabels) { + if (label.config.selected) { + [allTags addObject:label.config]; + } + } + + return [allTags copy]; +} + +- (NSArray *)allNotSelectedTags { + NSMutableArray *allTags = [NSMutableArray new]; + + for (TTGTextTagComponentView *label in _tagLabels) { + if (label.config && !label.config.selected) { + [allTags addObject:label.config]; + } + } + + return [allTags copy]; +} + +- (NSInteger)indexOfTagAtPoint:(CGPoint)point { + CGPoint convertedPoint = [self convertPoint:point toView:_tagCollectionView]; + return [_tagCollectionView indexOfTagAt:convertedPoint]; +} + +#pragma mark - TTGTagCollectionViewDataSource + +- (NSUInteger)numberOfTagsInTagCollectionView:(TTGTagCollectionView *)tagCollectionView { + return _tagLabels.count; +} + +- (UIView *)tagCollectionView:(TTGTagCollectionView *)tagCollectionView tagViewForIndex:(NSUInteger)index { + return _tagLabels[index]; +} + +#pragma mark - TTGTagCollectionViewDelegate + +- (BOOL)tagCollectionView:(TTGTagCollectionView *)tagCollectionView shouldSelectTag:(UIView *)tagView atIndex:(NSUInteger)index { + if (_enableTagSelection) { + TTGTextTagComponentView *label = _tagLabels[index]; + + if ([self.delegate respondsToSelector:@selector(textTagCollectionView:canTapTag:atIndex:)]) { + return [self.delegate textTagCollectionView:self canTapTag:label.config atIndex:index]; + } else { + return YES; + } + } else { + return NO; + } +} + +- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView didSelectTag:(UIView *)tagView atIndex:(NSUInteger)index { + if (_enableTagSelection) { + TTGTextTagComponentView *label = _tagLabels[index]; + + + if (_selectionLimit == 1) { + for (TTGTextTagComponentView *tag in _tagLabels) { + tag.config.selected = false; + } + } + + label.config.selected = !label.config.selected; + + if (self.alignment == TTGTagCollectionAlignmentFillByExpandingWidth || + self.alignment == TTGTagCollectionAlignmentFillByExpandingWidthExceptLastLine) { + [self reload]; + } else { + [self updateStyleAndFrameForLabel:label]; + } + + if ([_delegate respondsToSelector:@selector(textTagCollectionView:didTapTag:atIndex:)]) { + [_delegate textTagCollectionView:self didTapTag:label.config atIndex:index]; + } + } +} + +- (CGSize)tagCollectionView:(TTGTagCollectionView *)tagCollectionView sizeForTagAtIndex:(NSUInteger)index { + return _tagLabels[index].frame.size; +} + +- (void)tagCollectionView:(TTGTagCollectionView *)tagCollectionView updateContentSize:(CGSize)contentSize { + if ([_delegate respondsToSelector:@selector(textTagCollectionView:updateContentSize:)]) { + [_delegate textTagCollectionView:self updateContentSize:contentSize]; + } +} + +#pragma mark - Setter and Getter + +- (UIScrollView *)scrollView { + return _tagCollectionView.scrollView; +} + +- (CGFloat)horizontalSpacing { + return _tagCollectionView.horizontalSpacing; +} + +- (void)setHorizontalSpacing:(CGFloat)horizontalSpacing { + _tagCollectionView.horizontalSpacing = horizontalSpacing; +} + +- (CGFloat)verticalSpacing { + return _tagCollectionView.verticalSpacing; +} + +- (void)setVerticalSpacing:(CGFloat)verticalSpacing { + _tagCollectionView.verticalSpacing = verticalSpacing; +} + +- (CGSize)contentSize { + return _tagCollectionView.contentSize; +} + +- (TTGTagCollectionScrollDirection)scrollDirection { + return _tagCollectionView.scrollDirection; +} + +- (void)setScrollDirection:(TTGTagCollectionScrollDirection)scrollDirection { + _tagCollectionView.scrollDirection = scrollDirection; +} + +- (TTGTagCollectionAlignment)alignment { + return _tagCollectionView.alignment; +} + +- (void)setAlignment:(TTGTagCollectionAlignment)alignment { + _tagCollectionView.alignment = alignment; +} + +- (NSUInteger)numberOfLines { + return _tagCollectionView.numberOfLines; +} + +- (void)setNumberOfLines:(NSUInteger)numberOfLines { + _tagCollectionView.numberOfLines = numberOfLines; +} + +- (NSUInteger)actualNumberOfLines { + return _tagCollectionView.actualNumberOfLines; +} + +- (UIEdgeInsets)contentInset { + return _tagCollectionView.contentInset; +} + +- (void)setContentInset:(UIEdgeInsets)contentInset { + _tagCollectionView.contentInset = contentInset; +} + +- (BOOL)manualCalculateHeight { + return _tagCollectionView.manualCalculateHeight; +} + +- (void)setManualCalculateHeight:(BOOL)manualCalculateHeight { + _tagCollectionView.manualCalculateHeight = manualCalculateHeight; +} + +- (CGFloat)preferredMaxLayoutWidth { + return _tagCollectionView.preferredMaxLayoutWidth; +} + +- (void)setPreferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth { + _tagCollectionView.preferredMaxLayoutWidth = preferredMaxLayoutWidth; +} + +- (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator { + _tagCollectionView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator; +} + +- (BOOL)showsHorizontalScrollIndicator { + return _tagCollectionView.showsHorizontalScrollIndicator; +} + +- (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator { + _tagCollectionView.showsVerticalScrollIndicator = showsVerticalScrollIndicator; +} + +- (BOOL)showsVerticalScrollIndicator { + return _tagCollectionView.showsVerticalScrollIndicator; +} + +- (void)setOnTapBlankArea:(void (^)(CGPoint location))onTapBlankArea { + _tagCollectionView.onTapBlankArea = onTapBlankArea; +} + +- (void (^)(CGPoint location))onTapBlankArea { + return _tagCollectionView.onTapBlankArea; +} + +- (void)setOnTapAllArea:(void (^)(CGPoint location))onTapAllArea { + _tagCollectionView.onTapAllArea = onTapAllArea; +} + +- (void (^)(CGPoint location))onTapAllArea { + return _tagCollectionView.onTapAllArea; +} + +#pragma mark - Private methods + +- (void)updateAllLabelStyleAndFrame { + for (TTGTextTagComponentView *label in _tagLabels) { + [self updateStyleAndFrameForLabel:label]; + } +} + +- (void)updateStyleAndFrameForLabel:(TTGTextTagComponentView *)label { + // Update content + [label updateContent]; + // Update content style + [label updateContentStyle]; + // Width limit for vertical scroll direction + CGSize maxSize = CGSizeZero; + if (self.scrollDirection == TTGTagCollectionScrollDirectionVertical && + CGRectGetWidth(self.bounds) > 0) { + maxSize.width = (CGRectGetWidth(self.bounds) - self.contentInset.left - self.contentInset.right); + } + // Update frame + [label updateFrameWithMaxSize:maxSize]; +} + +- (TTGTextTagComponentView *)newLabelWithConfig:(TTGTextTag *)config { + TTGTextTagComponentView *label = [TTGTextTagComponentView new]; + label.config = config; + return label; +} + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagContent.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagContent.h new file mode 100644 index 00000000..5a544959 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagContent.h @@ -0,0 +1,23 @@ +// +// TTGTextTagContent.h +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import + +/** + Base content class. + Do not use this class directly! + */ +@interface TTGTextTagContent : NSObject + +/// Must be override by subClass +- (NSAttributedString *_Nonnull)getContentAttributedString; + +/// Must be override by subClass +- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagContent.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagContent.m new file mode 100644 index 00000000..0a98b118 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagContent.m @@ -0,0 +1,22 @@ +// +// TTGTextTagContent.m +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagContent.h" + +@implementation TTGTextTagContent + +- (NSAttributedString *)getContentAttributedString { + NSAssert(NO, @"Do not use TTGTextTagContent directly."); + return [NSAttributedString new]; +} + +- (id)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] init]; +} + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStringContent.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStringContent.h new file mode 100644 index 00000000..f49e4407 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStringContent.h @@ -0,0 +1,39 @@ +// +// TTGTextTagStringContent.h +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagContent.h" + +/** + Normal text content with custom font and color. + */ +@interface TTGTextTagStringContent : TTGTextTagContent + +/// Text +@property (nonatomic, copy) NSString * _Nonnull text; +/// Text font +@property (nonatomic, copy) UIFont * _Nonnull textFont; +/// Text color +@property (nonatomic, copy) UIColor * _Nonnull textColor; + +/// Init +- (instancetype _Nonnull)initWithText:(NSString *_Nonnull)text; +- (instancetype _Nonnull)initWithText:(NSString *_Nonnull)text + textFont:(UIFont *_Nullable)textFont + textColor:(UIColor *_Nullable)textColor; + +/// Content ++ (instancetype _Nonnull)contentWithText:(NSString *_Nonnull)text; ++ (instancetype _Nonnull)contentWithText:(NSString *_Nonnull)text + textFont:(UIFont *_Nullable)textFont + textColor:(UIColor *_Nullable)textColor; + +/// Base system methods +- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone; +- (NSString *_Nonnull)description; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStringContent.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStringContent.m new file mode 100644 index 00000000..a36ba59e --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStringContent.m @@ -0,0 +1,80 @@ +// +// TTGTextTagStringContent.m +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagStringContent.h" + +@implementation TTGTextTagStringContent + +- (instancetype)initWithText:(NSString *)text { + self = [super init]; + if (self) { + self.text = text; + } + return self; +} + ++ (instancetype)contentWithText:(NSString *)text { + return [[self alloc] initWithText:text]; +} + +- (instancetype)initWithText:(NSString *)text + textFont:(UIFont *)textFont + textColor:(UIColor *)textColor { + self = [super init]; + if (self) { + self.text = text; + self.textFont = textFont; + self.textColor = textColor; + } + return self; +} + ++ (instancetype)contentWithText:(NSString *)text + textFont:(UIFont *)textFont + textColor:(UIColor *)textColor { + return [[self alloc] initWithText:text + textFont:textFont + textColor:textColor]; +} + +- (NSAttributedString *)getContentAttributedString { + return [[NSAttributedString alloc] initWithString:self.text + attributes:@{NSForegroundColorAttributeName: self.textColor, + NSFontAttributeName: self.textFont}]; +} + +- (NSString *)text { + return _text ?: @""; +} + +- (UIFont *)textFont { + return _textFont ?: [UIFont systemFontOfSize:14]; +} + +- (UIColor *)textColor { + return _textColor ?: [UIColor blackColor]; +} + +- (id)copyWithZone:(NSZone *)zone { + TTGTextTagStringContent *copy = (TTGTextTagStringContent *)[super copyWithZone:zone]; + if (copy != nil) { + copy.text = self.text; + copy.textFont = self.textFont; + copy.textColor = self.textColor; + } + return copy; +} + +- (NSString *)description { + NSMutableString *description = [NSMutableString stringWithFormat:@"<%@: ", NSStringFromClass([self class])]; + [description appendFormat:@"self.text=%@", self.text]; + [description appendString:@">"]; + return description; +} + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStyle.h b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStyle.h new file mode 100644 index 00000000..ddffdeb3 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStyle.h @@ -0,0 +1,65 @@ +// +// TTGTextTagStyle.h +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import +#import + +@interface TTGTextTagStyle : NSObject + +/// Background color +@property (nonatomic, copy) UIColor * _Nonnull backgroundColor; // Default is [UIColor lightGrayColor] + +/// Text alignment +@property (nonatomic, assign) NSTextAlignment textAlignment; // Default is NSTextAlignmentCenter + +/// Gradient background color +@property (nonatomic, assign) BOOL enableGradientBackground; // Default is NO +@property (nonatomic, copy) UIColor * _Nonnull gradientBackgroundStartColor; +@property (nonatomic, copy) UIColor * _Nonnull gradientBackgroundEndColor; +@property (nonatomic, assign) CGPoint gradientBackgroundStartPoint; +@property (nonatomic, assign) CGPoint gradientBackgroundEndPoint; + +/// Corner radius +@property (nonatomic, assign) CGFloat cornerRadius; // Default is 4 +@property (nonatomic, assign) Boolean cornerTopRight; +@property (nonatomic, assign) Boolean cornerTopLeft; +@property (nonatomic, assign) Boolean cornerBottomRight; +@property (nonatomic, assign) Boolean cornerBottomLeft; + +/// Border +@property (nonatomic, assign) CGFloat borderWidth; // Default is [UIColor whiteColor] +@property (nonatomic, copy) UIColor * _Nonnull borderColor; // Default is 1 + +/// Shadow. +@property (nonatomic, copy) UIColor * _Nonnull shadowColor; // Default is [UIColor blackColor] +@property (nonatomic, assign) CGSize shadowOffset; // Default is (2, 2) +@property (nonatomic, assign) CGFloat shadowRadius; // Default is 2f +@property (nonatomic, assign) CGFloat shadowOpacity; // Default is 0.3f + +/// Extra space in width and height, will expand each tag's size +@property (nonatomic, assign) CGSize extraSpace; + +/// Max width for a text tag. 0 and below means no max width. +@property (nonatomic, assign) CGFloat maxWidth; +/// Min width for a text tag. 0 and below means no min width. +@property (nonatomic, assign) CGFloat minWidth; + +/// Max height for a text tag. 0 and below means no max height. +@property (nonatomic, assign) CGFloat maxHeight; +/// Min height for a text tag. 0 and below means no min height. +@property (nonatomic, assign) CGFloat minHeight; + +/// Exact width. 0 and below means no work +@property (nonatomic, assign) CGFloat exactWidth; +/// Exact height. 0 and below means no work +@property (nonatomic, assign) CGFloat exactHeight; + +/// Copy +- (id _Nonnull)copyWithZone:(NSZone *_Nullable)zone; + +@end diff --git a/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStyle.m b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStyle.m new file mode 100644 index 00000000..43629e51 --- /dev/null +++ b/QuickLocation/UIKit/TTGTagCollectionView/TTGTextTagStyle.m @@ -0,0 +1,84 @@ +// +// TTGTextTagStyle.m +// TTGTagCollectionView +// +// Created by zekunyan on 2019/5/24. +// Copyright (c) 2021 zekunyan. All rights reserved. +// + +#import "TTGTextTagStyle.h" + +@implementation TTGTextTagStyle + +- (instancetype)init { + self = [super init]; + if (self) { + _backgroundColor = [UIColor lightGrayColor]; + _textAlignment = NSTextAlignmentCenter; + _enableGradientBackground = NO; + _cornerRadius = 4; + _borderColor = [UIColor whiteColor]; + _borderWidth = 1; + _shadowColor = [UIColor blackColor]; + _shadowOffset = CGSizeMake(2, 2); + _shadowRadius = 2; + _shadowOpacity = 0.3; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + TTGTextTagStyle *copy = (TTGTextTagStyle *)[[[self class] allocWithZone:zone] init]; + + if (copy != nil) { + copy.backgroundColor = self.backgroundColor; + copy.textAlignment = self.textAlignment; + copy.enableGradientBackground = self.enableGradientBackground; + copy.gradientBackgroundStartColor = self.gradientBackgroundStartColor; + copy.gradientBackgroundEndColor = self.gradientBackgroundEndColor; + copy.gradientBackgroundStartPoint = self.gradientBackgroundStartPoint; + copy.gradientBackgroundEndPoint = self.gradientBackgroundEndPoint; + copy.cornerRadius = self.cornerRadius; + copy.cornerTopRight = self.cornerTopRight; + copy.cornerTopLeft = self.cornerTopLeft; + copy.cornerBottomRight = self.cornerBottomRight; + copy.cornerBottomLeft = self.cornerBottomLeft; + copy.borderWidth = self.borderWidth; + copy.borderColor = self.borderColor; + copy.shadowColor = self.shadowColor; + copy.shadowOffset = self.shadowOffset; + copy.shadowRadius = self.shadowRadius; + copy.shadowOpacity = self.shadowOpacity; + copy.extraSpace = self.extraSpace; + copy.maxWidth = self.maxWidth; + copy.minWidth = self.minWidth; + copy.maxHeight = self.maxHeight; + copy.minHeight = self.minHeight; + copy.exactWidth = self.exactWidth; + copy.exactHeight = self.exactHeight; + } + + return copy; +} + +- (UIColor *)backgroundColor { + return _backgroundColor ?: [UIColor clearColor]; +} + +- (UIColor *)gradientBackgroundStartColor { + return _gradientBackgroundStartColor ?: [UIColor clearColor]; +} + +- (UIColor *)gradientBackgroundEndColor { + return _gradientBackgroundEndColor ?: [UIColor clearColor]; +} + +- (UIColor *)borderColor { + return _borderColor ?: [UIColor clearColor]; +} + +- (UIColor *)shadowColor { + return _shadowColor ?: [UIColor clearColor]; +} + +@end diff --git a/QuickLocation/ViewController.swift b/QuickLocation/ViewController.swift new file mode 100644 index 00000000..f928350b --- /dev/null +++ b/QuickLocation/ViewController.swift @@ -0,0 +1,18 @@ +// +// ViewController.swift +// QuickLocation +// +// Created by 林 on 2026/5/25. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view. + } + + +}