{"id":20685007,"url":"https://github.com/geri-borbas/ios.package.withable","last_synced_at":"2025-04-22T13:39:24.704Z","repository":{"id":41228607,"uuid":"479715612","full_name":"Geri-Borbas/iOS.Package.Withable","owner":"Geri-Borbas","description":"📐 Declarative UIKit in 10 lines of code.","archived":false,"fork":false,"pushed_at":"2022-04-19T11:27:52.000Z","size":2329,"stargazers_count":28,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-15T08:02:01.858Z","etag":null,"topics":["builder-pattern","declarative","declarative-programming","declarative-ui","decorator-pattern","ios","swift","swift-package","swift-package-manager","uikit"],"latest_commit_sha":null,"homepage":"https://blog.eppz.eu/declarative-uikit-with-10-lines-of-code/","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Geri-Borbas.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-04-09T12:11:18.000Z","updated_at":"2024-09-30T18:59:59.000Z","dependencies_parsed_at":"2022-09-01T23:41:36.822Z","dependency_job_id":null,"html_url":"https://github.com/Geri-Borbas/iOS.Package.Withable","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Geri-Borbas%2FiOS.Package.Withable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Geri-Borbas%2FiOS.Package.Withable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Geri-Borbas%2FiOS.Package.Withable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Geri-Borbas%2FiOS.Package.Withable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Geri-Borbas","download_url":"https://codeload.github.com/Geri-Borbas/iOS.Package.Withable/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224976382,"owners_count":17401390,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["builder-pattern","declarative","declarative-programming","declarative-ui","decorator-pattern","ios","swift","swift-package","swift-package-manager","uikit"],"created_at":"2024-11-16T22:25:04.622Z","updated_at":"2024-11-16T22:25:05.069Z","avatar_url":"https://github.com/Geri-Borbas.png","language":"Swift","readme":"# Withable\n\n📐 Declarative UIKit in 10 lines of code.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"Documentation/Declarative_UIKit_with_10_lines_of_code_SwiftUI_Xcode_Preview.png\" width=\"900\"\u003e\u003c/p\u003e\n\nSee corresponding article at [**Declarative UIKit with 10 lines of code** A simple extension instead of libraries] for more.\n\n\n## How to use\n\nWith a **single extension** on `AnyObject` you can do things like this.\n\n```Swift\nclass ContentViewController: UIViewController {\n    \n    ...\n    \n    lazy var titleLabel = UILabel()\n        .with {\n            $0.text = viewModel.title\n            $0.textColor = .label\n            $0.font = .preferredFont(forTextStyle: .largeTitle)\n        }\n    \n    ...\n}\n```\n\nWith **any kind of object**, really.\n\n```Swift\nlazy var submitButton = UIButton()\n    .with {\n        $0.setTitle(\"Submit\", for: .normal)\n        $0.addTarget(self, action: #selector(didTapSubmitButton), for: .touchUpInside)\n    }\n```\n\n```Swift\npresent(\n    DetailViewController()\n        .with {\n            $0.modalTransitionStyle = .crossDissolve\n            $0.modalPresentationStyle = .overCurrentContext\n        },\n    animated: true\n)\n```\n\n```Swift\npresent(\n    UIAlertController(title: title, message: message, preferredStyle: .alert)\n        .with {\n            $0.addAction(UIAlertAction(title: \"Ok\", style: .default, handler: nil))\n        },\n    animated: true\n)\n```\n\n```Swift\nlet today = DateFormatter()\n    .with {\n        $0.dateStyle = .medium\n        $0.locale = Locale(identifier: \"en_US\")\n    }\n    .string(from: Date())\n```\n\n```Swift\nlazy var displayLink = CADisplayLink(target: self, selector: #selector(update))\n    .with {\n        $0.isPaused = true\n        $0.preferredFramesPerSecond = 120\n        $0.add(to: RunLoop.main, forMode: .common)\n    }\n```\n\nEven value types as well (after conforming to `Withable`). \n\n```Swift\nextension PersonNameComponents: Withable { }\n\nlet name = PersonNameComponents()\n    .with {\n        $0.givenName = \"Geri\"\n        $0.familyName = \"Borbás\"\n    }\n```\n\nNot to mention 3D stuff (`ARKit`, `RealityKit`, `SceneKit`).\n\n```Swift\nview.scene.addAnchor(\n    AnchorEntity(plane: .horizontal)\n        .with {\n            $0.addChild(\n                ModelEntity(\n                    mesh: MeshResource.generateBox(size: 0.3),\n                    materials: [\n                        SimpleMaterial(color: .green, isMetallic: true)\n                    ]\n                )\n            )\n        }\n)\n```\n\n\n## How it works\n\nIt is implemented in this `with` method. 💎\n\n```Swift\npublic extension Withable {\n    \n    func with(_ closure: (Self) -\u003e Void) -\u003e Self {\n        closure(self)\n        return self\n    }\n}\n```\n\nThe method implements pretty **classic patterns**. You can think of it as something between an unspecialized/parametric builder, or a **decorator** with customizable/pluggable decorating behaviour. See [`Withable.swift`] for all details (generics, value types). \n\n\n## UIKit benefits\n\nThe package contains a couple of **convinient extensions** of `UIKit` classes what I use (probably will be moved to their own package as they grow). I left them here intentionally as they may exemplify how you can **create your own extensions** tailored for your codebases' needs.\n\nFor example, you may create a convenient **`text` decorator** for `UILabel`.\n\n```Swift\nextension UILabel {\n    \n    func with(text: String?) -\u003e Self {\n        with {\n            $0.text = text\n        }\n    }\n}\n```\n\nFurthermore, you can condense your **styles to simple extensions** like this.\n\n```Swift\nextension UILabel {\n    \n    var withTitleStyle: Self {\n        with {\n            $0.textColor = .label\n            $0.font = .preferredFont(forTextStyle: .largeTitle)\n        }\n    }\n    \n    var withPropertyStyle: Self {\n        with {\n            $0.textColor = .systemBackground\n            $0.font = .preferredFont(forTextStyle: .headline)\n            $0.setContentCompressionResistancePriority(.required, for: .vertical)\n        }\n    }\n    \n    var withPropertyValueStyle: Self {\n        with {\n            $0.textColor = .systemGray\n            $0.font = .preferredFont(forTextStyle: .body)\n        }\n    }\n    \n    var withParagraphStyle: Self {\n        with {\n            $0.textColor = .label\n            $0.numberOfLines = 0\n            $0.font = .preferredFont(forTextStyle: .footnote)\n        }\n    }\n}\n```\n\nWith extensions like that, you can clean up view controllers.\n\n```Swift\nclass ContentViewController: UIViewController {\n    \n    let viewModel = Planets().earth\n    \n    private lazy var body = UIStackView().vertical(spacing: 10).views(\n        UILabel()\n            .with(text: viewModel.title)\n            .withTitleStyle,\n        UIStackView().vertical(spacing: 5).views(\n            UIStackView().horizontal(spacing: 5).views(\n                UILabel()\n                    .with(text: \"size\")\n                    .withPropertyStyle\n                    .withBox,\n                UILabel()\n                    .with(text: viewModel.properties.size)\n                    .withPropertyValueStyle,\n                UIView.spacer\n            ),\n            UIStackView().horizontal(spacing: 5).views(\n                UILabel()\n                    .with(text: \"distance\")\n                    .withPropertyStyle\n                    .withBox,\n                UILabel()\n                    .with(text: viewModel.properties.distance)\n                    .withPropertyValueStyle,\n                UIView.spacer\n            ),\n            UIStackView().horizontal(spacing: 5).views(\n                UILabel()\n                    .with(text: \"mass\")\n                    .withPropertyStyle\n                    .withBox,\n                UILabel()\n                    .with(text: viewModel.properties.mass)\n                    .withPropertyValueStyle,\n                UIView.spacer\n            )\n        ),\n        UIImageView()\n            .with(image: UIImage(named: viewModel.imageAssetName)),\n        UILabel()\n            .with(text: viewModel.paragraphs.first)\n            .withParagraphStyle,\n        UILabel()\n            .with(text: viewModel.paragraphs.last)\n            .withParagraphStyle,\n        UIView.spacer\n    )\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        view.addSubview(body)\n        view.backgroundColor = .systemBackground\n        body.pin(\n            to: view.safeAreaLayoutGuide,\n            insets: UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)\n        )\n    }\n}\n```\n\nI recommend to read the corresponding article at [**Declarative UIKit with 10 lines of code** A simple extension instead of libraries] to read more about the background and more examples.\n\n\n## Used by Apple\n\nLater on, I found out that on occasions **Apple uses the very same pattern** to enable decorating objects inline. These decorator functions are even uses the same `with` naming convention.\n\nThese examples below are in vanilla `UIKit`. 🍦\n\n```Swift\nlet arrow = UIImage(named: \"Arrow\").withTintColor(.blue)\nlet mail = UIImage(systemName: \"envelope\").withRenderingMode(.alwaysTemplate)\nlet color = UIColor.label.withAlphaComponent(0.5)\n```\n    \n* [`UIImage.withTintColor(_:)`]\n* [`UIImage.withAlphaComponent(_:)`]\n* [`UIImage.Configuration.withTraitCollection(_:)`]\n* More examples in [`UIImage.Configuration`]\n\n\n## Stored properties in extensions\n\nIn addition, the package contains an `NSObject` extension that helps creating **stored properties in extensions**. I ended up including it because I found extending `UIKit` classes with stored properties is a pretty common usecase. See [`NSObject+Extensions.swift`] and [`UIButton+Extensions.swift`] for more.\n\nYou can do things like this.\n\n```Swift\nextension UITextField {\n    \n    var nextTextField: UITextField? {\n        get {\n            associatedObject(for: \"nextTextField\") as? UITextField\n        }\n        set {\n            set(associatedObject: newValue, for: \"nextTextField\")\n        }\n    }\n}\n```\n\n\n## Declare constraints inline\n\nOne more secret weapon is the [`UIView.onMoveToSuperview`] extension, which is simply a closure called (once) when the `view` gets added to a `superview`. With that, you can declare the constraints in advance using this closure at initialization time, then they are added/activated later on at runtime by the time when the view has a superview. See [Keyboard Avoidance] repository for usage examples.\n\n\n## License\n\n\u003e Licensed under the [**MIT License**](https://en.wikipedia.org/wiki/MIT_License).\n\n\n[`Withable.swift`]: Withable/Withable.swift\n[**Declarative UIKit with 10 lines of code** A simple extension instead of libraries]: https://blog.eppz.eu/declarative-uikit-with-10-lines-of-code/\n[`NSObject+Extensions.swift`]: Withable/NSObject+Extensions.swift\n[`UIButton+Extensions.swift`]: Withable/UI/UIButton+Extensions.swift\n[`UIImage.withTintColor(_:)`]: https://developer.apple.com/documentation/uikit/uiimage/3327300-withtintcolor\n[`UIImage.withAlphaComponent(_:)`]: https://developer.apple.com/documentation/uikit/uicolor/1621922-withalphacomponent\n[`UIImage.Configuration.withTraitCollection(_:)`]: https://developer.apple.com/documentation/uikit/uiimage/configuration/3295946-withtraitcollection\n[`UIImage.Configuration`]: https://developer.apple.com/documentation/uikit/uiimage/configuration\n[`UIView.onMoveToSuperview`]: Withable/UIView+Extensions.swift\n[Keyboard Avoidance]: https://github.com/Geri-Borbas/iOS.Blog.Keyboard_Avoidance\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgeri-borbas%2Fios.package.withable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgeri-borbas%2Fios.package.withable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgeri-borbas%2Fios.package.withable/lists"}