├── .github ├── actions │ └── setup │ │ └── action.yml └── workflows │ └── ios.yml ├── .gitignore ├── CHANGELOG.md ├── Gemfile ├── Gemfile.lock ├── LICENSE ├── Package.swift ├── README.md ├── Rakefile ├── Sources └── ReadabilityModifier │ ├── Extension │ ├── UIApplication+Extension.swift │ └── View+Extension.swift │ ├── Utility │ ├── GeometryGetter.swift │ ├── ReadableContentGuideType.swift │ └── UnderlyingViewController.swift │ └── ViewModifier │ └── ReadableContentGuideViewModifier.swift ├── Tests └── ReadabilityModifierTests │ ├── ReadabilityModifierTestView.swift │ ├── ReadabilityModifierTests.swift │ ├── TestUtility.swift │ └── UnderlyingViewControllerTests.swift └── example_images ├── example_with_modifier.png └── example_without_modifier.png /.github/actions/setup/action.yml: -------------------------------------------------------------------------------- 1 | name: Setup 2 | description: Setup iOS CI Environment 3 | runs: 4 | using: composite 5 | steps: 6 | - name: Install Ruby Gems 7 | run: bundle install 8 | shell: bash -------------------------------------------------------------------------------- /.github/workflows/ios.yml: -------------------------------------------------------------------------------- 1 | name: Test Workflow 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | test-package: 11 | name: "Test Package" 12 | runs-on: macos-latest 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | - uses: ruby/setup-ruby@v1 18 | with: 19 | ruby-version: '2.7' 20 | bundler-cache: true 21 | - name: Run Tests 22 | run: bundle exec rake test:package -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /Packages 3 | /*.xcodeproj 4 | xcuserdata/ 5 | DerivedData/ 6 | .netrc 7 | .idea 8 | *.ipa 9 | 10 | 11 | # AppCode 12 | .idea/ 13 | 14 | # other 15 | build/ 16 | *.psd 17 | 18 | # macOS 19 | .DS_Store 20 | 21 | # Swift Package Manager 22 | .swiftpm 23 | .build/ 24 | Package.resolved 25 | 26 | # Test artifacts 27 | Tests/Artifacts -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## Version 1.0 4 | 5 | * Initial release -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' do 2 | gem "rake", "~> 13.0.0" 3 | end -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | specs: 3 | 4 | GEM 5 | remote: https://rubygems.org/ 6 | specs: 7 | rake (13.0.6) 8 | 9 | PLATFORMS 10 | ruby 11 | 12 | DEPENDENCIES 13 | rake (~> 13.0.0)! 14 | 15 | BUNDLED WITH 16 | 2.3.14 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2022 YAZIO GmbH 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.5 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "ReadabilityModifier", 8 | defaultLocalization: "en", 9 | platforms: [ 10 | .iOS("14.0"), 11 | ], 12 | products: [ 13 | .library( 14 | name: "ReadabilityModifier", 15 | targets: ["ReadabilityModifier"]), 16 | ], 17 | dependencies: [], 18 | targets: [ 19 | .target( 20 | name: "ReadabilityModifier", 21 | dependencies: []), 22 | .testTarget( 23 | name: "ReadabilityModifierTests", 24 | dependencies: ["ReadabilityModifier"]), 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Test package](https://github.com/yazio/ReadabilityModifier/actions/workflows/ios.yml/badge.svg) 2 | 3 | ReadabilityModifier 4 | =============================== 5 | 6 | > UIKits readableContentGuide for every SwiftUI View, in the form of a ViewModifier 7 | 8 | What it is 9 | ---------- 10 | 11 | Displaying multiple lines of text in a single column can make it hard to read the text and easy to lose track of the lines - especially on devices with a great screen width, like iPads. 12 | 13 | ### With the modifier applied: 14 | ![](example_images/example_with_modifier.png) 15 | 16 | ### Without the modifier: 17 | ![](example_images/example_without_modifier.png) 18 | 19 | With iOS 9.0, Apple introduced [readableContentGuide](https://developer.apple.com/documentation/uikit/uiview/1622644-readablecontentguide) - a layout guide representing an area with a readable width within the view. 20 | 21 | UI components that follow this layout guide automatically adjust their width accordingly to provide a better reading experience, while taking screen size, orientation, multitasking and even dynamic type size into account. 22 | 23 | What this package does 24 | ---------------------- 25 | 26 | Since readableContentGuide is part of UIKit, there is no direct alternative in SwiftUI. Alternative solutions, like applying a bigger padding depending on the horizontal size class, do not consider the variety of combinations of screen size, dynamic type size, etc. 27 | 28 | ReadabilityModifier provides a simple ViewModifier that ports the original behavior of UIKits readableContentGuide to every SwiftUI View that it is applied to - either by setting the width of the view, or by adding horizontal padding. 29 | 30 | Usage 31 | ----- 32 | 33 | Apply .fitToReadableContentGuide() on any SwiftUI View to add horizontal padding that places the view inside the readableContentGuide 34 | ```swift 35 | var body: some View { 36 | VStack { 37 | Text("This text could be waaaaay longer...") 38 | .fitToReadableContentGuide() 39 | } 40 | } 41 | ``` 42 | You can add extra spacing that is added on top of the readableContentGuide 43 | ```swift 44 | Text("This text needs some more room") 45 | .fitToReadableContentGuide(extraSpacing: 20) 46 | ``` 47 | The default way the readableContentGuide is respected is by adding a horizontal padding to the view. In some cases, e.g. when the view is already placed in a VStack that already has padding, this padding will add up and make the text smaller than intended. By changing the type property, you can also set the width of the view - this uses the .frame() function to respect the readableContentGuide 48 | ```swift 49 | VStack { 50 | Text("This text is already in a padded container, so I will rather set its width") 51 | .fitToReadableContentGuide(type: .width) 52 | } 53 | .padding(100) 54 | ``` 55 | 56 | Install 57 | ------- 58 | 59 | ### Adding ReadabilityModifier as a package dependency 60 | 61 | 1. Go to `Xcode` -> `Project Settings` and select your Project 62 | 2. Select Tab `Package Dependencies` and click the + 63 | 3. Paste `https://github.com/yazio/ReadabilityModifier` in the search bar and click on "Add Package" 64 | 4. Select the target(s) in which you want to use ReadabilityModifier 65 | 66 | ### Swift Package Manager 67 | 68 | Add ReadabilityModifier as a package dependency, like shown in the example below: 69 | ```swift 70 | // swift-tools-version:5.6 71 | 72 | import PackageDescription 73 | 74 | let package = Package( 75 | name: "YourProject", 76 | platforms: [ 77 | .iOS(.v14), 78 | ], 79 | dependencies: [ 80 | .package(name: "ReadabilityModifier", url: "https://github.com/yazio/ReadabilityModifier.git", .branch("main")) 81 | ], 82 | targets: [ 83 | .target(name: "YourProject", dependencies: ["ReadabilityModifier"]) 84 | ] 85 | ) 86 | ``` 87 | 88 | We are hiring 89 | ------------- 90 | 91 | If you are interested in working on a well architected Nutrition & Health-App in a fully remote position, we'd love to hear from you! [Check our open positions](https://www.yazio.com/en/jobs) and feel free to reach out if you have any questions. 92 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | namespace :test do 2 | desc 'Run tests for ReadabilityModifier' 3 | task :package do 4 | sh 'rm -rf Tests/Artifacts' 5 | sh 'xcodebuild test -scheme ReadabilityModifier -destination "platform=iOS Simulator,name=iPhone 13 Pro,OS=15.2" -resultBundlePath Tests/Artifacts/ReadabilityModifierTests.xcresult' 6 | end 7 | end -------------------------------------------------------------------------------- /Sources/ReadabilityModifier/Extension/UIApplication+Extension.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | public extension UIApplication 4 | { 5 | /// 6 | /// Returns `true` when if the app is running on an iPad in splitscreen mode 7 | /// 8 | var isSplitOrSlideOver: Bool 9 | { 10 | guard let window = windows 11 | .filter(\.isKeyWindow) 12 | .first 13 | else { return false } 14 | return !(window.frame.width == window.screen.bounds.width) 15 | } 16 | 17 | /// 18 | /// Returns the safeAreaInsets of the currently displayed window 19 | /// 20 | var safeAreaInsets: UIEdgeInsets 21 | { 22 | UIApplication.shared.windows.first?.safeAreaInsets ?? UIEdgeInsets.zero 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Sources/ReadabilityModifier/Extension/View+Extension.swift: -------------------------------------------------------------------------------- 1 | import SwiftUI 2 | 3 | public extension View 4 | { 5 | /// Modifies width of a SwiftUI View by using UIViews readableContentGuide. Also observes orientation and size changes to force a redraw. 6 | /// - Parameter extraSpacing: Adds more horizontal spacing 7 | /// - Parameter type: Select if the Readable Content Guide should be respected by applying eiter a horizontal padding or by 8 | /// - Returns: The view that the readableContentGuide padding is applied to 9 | func fitToReadableContentGuide( 10 | extraSpacing: CGFloat = 0, 11 | type: ReadableContentGuideType = .padding 12 | ) -> some View 13 | { 14 | modifier( 15 | ReadableContentGuideViewModifier( 16 | extraSpacing: extraSpacing, 17 | readableContentGuideType: type 18 | ) 19 | ) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Sources/ReadabilityModifier/Utility/GeometryGetter.swift: -------------------------------------------------------------------------------- 1 | import SwiftUI 2 | 3 | /// Place this struct as a background of the view to get its frame outside of its scope 4 | /// - Parameter rect: A binding of the CGRect that observes the frame of the View 5 | struct GeometryGetter: View 6 | { 7 | @Binding var rect: CGRect 8 | 9 | init(rect: Binding) 10 | { 11 | self._rect = rect 12 | } 13 | 14 | var body: some View 15 | { 16 | GeometryReader 17 | { 18 | geometry in 19 | 20 | makeView(geometry: geometry) 21 | } 22 | } 23 | 24 | private func makeView(geometry: GeometryProxy) -> some View 25 | { 26 | DispatchQueue.main.async 27 | { 28 | self.rect = geometry.frame(in: .global) 29 | } 30 | return Rectangle().fill(Color.clear) 31 | } 32 | } 33 | 34 | /// Place this struct as a background of the view to get its frame outside of its scope 35 | /// - Parameter rect: A binding of the CGRect that observes the frame of the View 36 | /// - Returns: The view that the readableContentGuide padding is applied to 37 | extension View 38 | { 39 | func observeFrame(rect: Binding) -> some View 40 | { 41 | background(GeometryGetter(rect: rect)) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Sources/ReadabilityModifier/Utility/ReadableContentGuideType.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// Enum to select if the ReadableContentGuide should be applied by adding padding or setting the width of a view. 4 | /// Can be helpful to avoid strange animations and to nest multiple views with readableContentGuide, so that the padding does not stack. 5 | public enum ReadableContentGuideType 6 | { 7 | case padding 8 | case width 9 | } 10 | -------------------------------------------------------------------------------- /Sources/ReadabilityModifier/Utility/UnderlyingViewController.swift: -------------------------------------------------------------------------------- 1 | import SwiftUI 2 | import UIKit 3 | 4 | extension View 5 | { 6 | func inject(_ view: SomeView) -> some View 7 | { 8 | overlay(view.frame(width: 0, height: 0)) 9 | } 10 | 11 | func underlyingViewController(customize: @escaping (UIViewController) -> ()) -> some View 12 | { 13 | inject( 14 | UIKitUnderlyingViewController( 15 | selector: \.parent, 16 | customize: customize 17 | ) 18 | ) 19 | } 20 | } 21 | 22 | class UnderlyingUIViewController: UIViewController 23 | { 24 | required init() 25 | { 26 | super.init(nibName: nil, bundle: nil) 27 | view = UnderlyingUIView() 28 | } 29 | 30 | @available(*, unavailable) 31 | required init?(coder _: NSCoder) 32 | { 33 | fatalError("init(coder:) has not been implemented") 34 | } 35 | } 36 | 37 | struct UIKitUnderlyingViewController: UIViewControllerRepresentable 38 | { 39 | let selector: (UnderlyingUIViewController) -> TargetViewControllerType? 40 | let customize: (TargetViewControllerType) -> Void 41 | 42 | init( 43 | selector: @escaping (UIViewController) -> TargetViewControllerType?, 44 | customize: @escaping (TargetViewControllerType) -> Void 45 | ) 46 | { 47 | self.selector = selector 48 | self.customize = customize 49 | } 50 | 51 | func makeUIViewController( 52 | context _: UIViewControllerRepresentableContext 53 | ) -> UnderlyingUIViewController 54 | { 55 | UnderlyingUIViewController() 56 | } 57 | 58 | func updateUIViewController( 59 | _ uiViewController: UnderlyingUIViewController, 60 | context _: UIViewControllerRepresentableContext 61 | ) 62 | { 63 | DispatchQueue.main.async 64 | { 65 | guard let targetView = selector(uiViewController) 66 | else 67 | { 68 | return 69 | } 70 | customize(targetView) 71 | } 72 | } 73 | } 74 | 75 | class UnderlyingUIView: UIView 76 | { 77 | required init() 78 | { 79 | super.init(frame: .zero) 80 | isHidden = true 81 | isUserInteractionEnabled = false 82 | } 83 | 84 | @available(*, unavailable) 85 | required init?(coder _: NSCoder) 86 | { 87 | fatalError("init(coder:) has not been implemented") 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Sources/ReadabilityModifier/ViewModifier/ReadableContentGuideViewModifier.swift: -------------------------------------------------------------------------------- 1 | import SwiftUI 2 | import UIKit 3 | 4 | /// Modifies width of a SwiftUI View by using UIViews readableContentGuide. Also observes orientation and size changes to force a redraw. 5 | /// - Parameter extraSpacing: Adds more horizontal spacing 6 | /// - Parameter type: Select if the Readable Content Guide should be respected by applying eiter a horizontal padding or by 7 | /// - Returns: The view that the readableContentGuide padding is applied to 8 | public struct ReadableContentGuideViewModifier: ViewModifier 9 | { 10 | @State private var horizontalPadding: CGFloat = 0 11 | @State private var width: CGFloat = 0 12 | 13 | private let extraSpacing: CGFloat 14 | private let readableContentGuideType: ReadableContentGuideType 15 | 16 | @State private var rect = CGRect.zero 17 | 18 | public init( 19 | extraSpacing: CGFloat = 0, 20 | readableContentGuideType: ReadableContentGuideType = .padding 21 | ) 22 | { 23 | self.extraSpacing = extraSpacing 24 | self.readableContentGuideType = readableContentGuideType 25 | } 26 | 27 | public func body( 28 | content: Content 29 | ) -> some View 30 | { 31 | if readableContentGuideType == .padding 32 | { 33 | applyCommonViewModifier(content: content) 34 | .padding(.horizontal, horizontalPadding) 35 | } 36 | else 37 | { 38 | applyCommonViewModifier(content: content) 39 | .frame(width: width, alignment: .center) 40 | } 41 | } 42 | 43 | @ViewBuilder 44 | private func applyCommonViewModifier( 45 | content: Content 46 | ) -> some View 47 | { 48 | Group 49 | { 50 | if isPadInSplitscreenMode 51 | { 52 | // iPad is in Splitscreen and should use introspect because initializing an empty UIViewController always uses the full screen size instead of the Splitscreen window 53 | content 54 | .underlyingViewController 55 | { 56 | viewController in 57 | 58 | updateWidthAndPadding(from: viewController) 59 | } 60 | // Observe so underlyingViewController gets called 61 | .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in } 62 | .onChange(of: rect, perform: { _ in }) 63 | } 64 | else 65 | { 66 | // Use own ViewController instance to get width 67 | content 68 | .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) 69 | { 70 | _ in 71 | 72 | updateWidthAndPadding() 73 | } 74 | .onChange(of: rect) 75 | { 76 | _ in 77 | 78 | updateWidthAndPadding() 79 | } 80 | .onAppear 81 | { 82 | updateWidthAndPadding() 83 | } 84 | } 85 | } 86 | .observeFrame(rect: $rect) 87 | } 88 | 89 | private func updateWidthAndPadding( 90 | from viewController: UIViewController = UIViewController() 91 | ) 92 | { 93 | let safeAreaInsets = UIApplication.shared.safeAreaInsets 94 | let safeArea = safeAreaInsets.left + safeAreaInsets.right 95 | horizontalPadding = (viewController.view.frame.width - viewController.view.readableContentGuide.layoutFrame.width + extraSpacing - safeArea) / 2 + (isPadInSplitscreenMode ? 0 : 16) 96 | width = (viewController.view.readableContentGuide.layoutFrame.width) - (isPadInSplitscreenMode ? 0 : 32) - extraSpacing 97 | } 98 | 99 | private var isPadInSplitscreenMode: Bool 100 | { 101 | UIApplication.shared.isSplitOrSlideOver 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Tests/ReadabilityModifierTests/ReadabilityModifierTestView.swift: -------------------------------------------------------------------------------- 1 | import ReadabilityModifier 2 | import SwiftUI 3 | 4 | struct ReadabilityModifierTestView: View 5 | { 6 | let contentGuideType: ReadableContentGuideType 7 | let extraSpacing: CGFloat 8 | let onWidthSet: (CGFloat) -> Void 9 | 10 | var body: some View 11 | { 12 | NavigationView 13 | { 14 | VStack 15 | { 16 | GeometryReader 17 | { 18 | geometry in 19 | 20 | Color.white 21 | .onChange(of: geometry.size.width) 22 | { 23 | newWidth in 24 | if newWidth > 0 25 | { 26 | onWidthSet(newWidth) 27 | } 28 | } 29 | } 30 | .fitToReadableContentGuide( 31 | extraSpacing: extraSpacing, 32 | type: contentGuideType 33 | ) 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Tests/ReadabilityModifierTests/ReadabilityModifierTests.swift: -------------------------------------------------------------------------------- 1 | @testable import ReadabilityModifier 2 | import SwiftUI 3 | import XCTest 4 | 5 | class ReadableContentGuideTests: XCTestCase 6 | { 7 | func testViewModifier_Padding() 8 | { 9 | let view = ReadabilityModifierTestView( 10 | contentGuideType: .padding, 11 | extraSpacing: 0 12 | ) 13 | { 14 | width in 15 | XCTAssertEqual(width, TestUtility.DeviceWidth.iPhone13Pro) 16 | } 17 | TestUtility.present(view: view) 18 | } 19 | 20 | func testViewModifier_Width() 21 | { 22 | let view = ReadabilityModifierTestView( 23 | contentGuideType: .padding, 24 | extraSpacing: 0 25 | ) 26 | { 27 | width in 28 | XCTAssertEqual(width, TestUtility.DeviceWidth.iPhone13Pro) 29 | } 30 | TestUtility.present(view: view) 31 | } 32 | 33 | func testViewModifier_extraSpacing_Padding() 34 | { 35 | let compareWidth = TestUtility.DeviceWidth.iPhone13Pro - TestUtility.Constant.extraSpacing 36 | let view = ReadabilityModifierTestView( 37 | contentGuideType: .padding, 38 | extraSpacing: TestUtility.Constant.extraSpacing 39 | ) 40 | { 41 | width in 42 | XCTAssertEqual(width, compareWidth) 43 | } 44 | TestUtility.present(view: view) 45 | } 46 | 47 | func testViewModifier_extraSpacing_Width() 48 | { 49 | let compareWidth = TestUtility.DeviceWidth.iPhone13Pro - TestUtility.Constant.extraSpacing 50 | let view = ReadabilityModifierTestView( 51 | contentGuideType: .padding, 52 | extraSpacing: TestUtility.Constant.extraSpacing 53 | ) 54 | { 55 | width in 56 | XCTAssertEqual(width, compareWidth) 57 | } 58 | TestUtility.present(view: view) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Tests/ReadabilityModifierTests/TestUtility.swift: -------------------------------------------------------------------------------- 1 | import SwiftUI 2 | 3 | enum TestUtility 4 | { 5 | enum DeviceWidth 6 | { 7 | static let iPhone13Pro: CGFloat = 358 8 | static let iPhone13Mini: CGFloat = 343 9 | } 10 | 11 | enum Constant 12 | { 13 | static let timeout: TimeInterval = 3 14 | static let extraSpacing: CGFloat = 25.4 15 | } 16 | 17 | static func present( 18 | view: ViewType 19 | ) 20 | { 21 | let hostingController = UIHostingController(rootView: view) 22 | 23 | let application = UIApplication.shared 24 | application.windows.forEach 25 | { 26 | window in 27 | if let presentedViewController = window.rootViewController?.presentedViewController 28 | { 29 | presentedViewController.dismiss( 30 | animated: false, 31 | completion: nil 32 | ) 33 | } 34 | window.isHidden = true 35 | } 36 | 37 | let window = UIWindow(frame: UIScreen.main.bounds) 38 | window.layer.speed = 10 39 | 40 | hostingController.beginAppearanceTransition(true, animated: false) 41 | window.rootViewController = hostingController 42 | window.makeKeyAndVisible() 43 | window.layoutIfNeeded() 44 | hostingController.endAppearanceTransition() 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Tests/ReadabilityModifierTests/UnderlyingViewControllerTests.swift: -------------------------------------------------------------------------------- 1 | @testable import ReadabilityModifier 2 | import SwiftUI 3 | import XCTest 4 | 5 | private struct UnderlyingViewControllerTestView: View 6 | { 7 | let completionHandler: () -> Void 8 | 9 | var body: some View 10 | { 11 | NavigationView 12 | { 13 | List 14 | { 15 | EmptyView() 16 | } 17 | } 18 | .underlyingViewController 19 | { 20 | _ in 21 | completionHandler() 22 | } 23 | } 24 | } 25 | 26 | class UnderlyingViewControllerTest: XCTestCase 27 | { 28 | func testViewController() 29 | { 30 | let expectation = XCTestExpectation() 31 | 32 | let view = UnderlyingViewControllerTestView 33 | { 34 | expectation.fulfill() 35 | } 36 | 37 | TestUtility.present(view: view) 38 | 39 | wait( 40 | for: [expectation], 41 | timeout: TestUtility.Constant.timeout 42 | ) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /example_images/example_with_modifier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yazio/ReadabilityModifier/f09cd02c31aff8bf2f787c68db832f2a166754e8/example_images/example_with_modifier.png -------------------------------------------------------------------------------- /example_images/example_without_modifier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yazio/ReadabilityModifier/f09cd02c31aff8bf2f787c68db832f2a166754e8/example_images/example_without_modifier.png --------------------------------------------------------------------------------