A swift PropertyWrapper to provide automatic NSView/UIView invalidation when the properties value changes.

Overview

@VIViewInvalidating

A swift PropertyWrapper to provide automatic NSView/UIView invalidation when the properties value changes. It duplicates the @Invalidating propertyWrapper for build targets prior to macOS 12 and iOS 15.

Swift Package Manager

Why?

I saw in the WWDC2021 video 'What's new in AppKit' they make a brief mention of a new propertyWrapper type @Invalidating() that automatically updates views when the wrappedValue is changed. It appears this propertyWrapper is only available in later versions of AppKit (and presumably UIKit).

Given that a lot of AppKit/UIKit devs aren't going to be able to move their minimum target version to macOS 12 or iOS 15 soon I decided to try to replicate what I saw in the video.

@VIViewInvalidating() was born!

And once your target is set to macOS 13 or above, your @VIViewInvalidating() definitions will generate deprecation warnings telling you to move to @Invalidating().

I've tried to make sure that the APIs are as close to @Invalidating as possible so moving your app target should in theory be as simple as changing some names

  • @VIViewInvalidating -> @Invalidating
  • VIViewCustomInvalidating -> UIViewInvalidating (for iOS/tvOS)
  • VIViewCustomInvalidating -> NSViewInvalidating (for macOS)

Invalidating types

Built-in

Provides built-in invalidators for

  • needsDisplay (.display)
  • needsLayout (.layout)
  • needsUpdateConstraints (.constraints)
  • invalidateIntrinsicContentSize() (.intrinsicContentSize)
  • invalidateRestorableState() (.restorableState) [macOS only]

Example

class BadgeView: NSView {
   // Automatically sets needsDisplay = true on the view when the value changes
   @VIViewInvalidating(.display) var color: NSColor = NSColor.blue
   
   // Set needsDisplay, needsLayout and invalidateIntrinsicContentSize() on 
   // the view when the value changes
   @VIViewInvalidating(.display, .layout, .intrinsicContentSize)
   var position: NSControl.ImagePosition = .imageLeft
}

Custom invalidation

Conforming your view to the VIViewCustomInvalidating protocol

The protocol method provides a very high-level callback when any of the @VIViewInvalidating properties are updated within your view. This is equivalent to the NSViewInvalidating protocol in later SDKs (macOS 12 and iOS 15)

Example

class BadgeView: NSView  {
   @VIViewInvalidating(.display) var color: NSColor = NSColor.blue
   @VIViewInvalidating(.display) var backgroundColor: NSColor = NSColor.white
}

extension BadgeView: VIViewCustomInvalidating {
   // Will be called when any `@VIViewInvalidating` property is updated in the view
   func invalidate(view: NSView) {
      Swift.print("custom invalidation!")
   }
}

Providing your own invalidator (not recommended!)

NOTE that this behaviour is NOT compatible with Apple's @Invalidating property wrapper. @Invalidating doesn't provide a similar functionality, so be aware when you move your build target up to macOS13/iOS15 there is no direct replacement so your code will break.

You can provide custom invalidators by defining a new class of type VIViewType.VIViewInvalidatorAction.

Example

class CustomInvalidator: VIViewInvalidatorAction {
   public override func invalidate(_ view: VIViewType) {
      Swift.print("Custom invalidator called")
   }
}

class ExcitingView: NSView {
   @VIViewInvalidating(.display) var color: NSColor = .white
   @VIViewInvalidating(.display, CustomInvalidator()) var backgroundColor: NSColor = .systemBlue
   override func draw(_ dirtyRect: NSRect) {
      self.backgroundColor.setFill()
      dirtyRect.fill()
   }
}

Updates

3.0.1

  • Fixed macOS demo linkage

3.0.0

2.0.1

  • Resolved Swift runtime crash when building in Xcode 11 and Swift 5.1. Previous version would crash the Swift runtime as it tries to resolve generic arguments for a class nested in an extension. Removing the nested extension containing the property wrapper (it wasn't required) solved the issue. This has no impact when compiling with Xcode 12 and above.

2.0.0

  • [BREAKING] Now that Apple has made @Invalidating available through Xcode, I've changed custom callback to match Apple's 'Invalidating' protocol to aid adoption when upgrading the SDK to one that supports @Invalidating.
  • [BREAKING] Changed the mechanism for handling custom invalidations.
  • Added restorableState as an invalidation type on macOS to be compatible with @Invalidating on macOS 12+

1.0.0

  • Initial release

Thanks

John Sundell

Twitter, Swift By Sundell

License

MIT. Use it for anything you want! Let me know if you do use it somewhere, I'd love to hear about it.

MIT License

Copyright (c) 2021 Darren Ford

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.
You might also like...
Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements
Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements

SwiftUIKitView Easily use UIKit views in SwiftUI. Convert UIView to SwiftUI View Create Xcode Previews from UIView elements SwiftUI functional updatin

📹 Framework to Play a Video in the Background of any UIView
📹 Framework to Play a Video in the Background of any UIView

SwiftVideoBackground is an easy to use Swift framework that provides the ability to play a video on any UIView. This provides a beautiful UI for login

Easily add drop shadows, borders, and round corners to a UIView.

Easily add drop shadows, borders, rounded corners to a UIView. Installation CocoaPods Add the follwing to your Podfile: pod 'Shades' Usage Storyboard

Anchorage - Single file UIView drag and drop system
Anchorage - Single file UIView drag and drop system

anchorage Single file UIView drag and drop system anchors.mp4 License Copyright

Super awesome Swift minion for Core Data (iOS, macOS, tvOS)

⚠️ Since this repository is going to be archived soon, I suggest migrating to NSPersistentContainer instead (available since iOS 10). For other conven

UI Component. This is a copy swipe-panel from app: Apple Maps, Stocks. Swift version
UI Component. This is a copy swipe-panel from app: Apple Maps, Stocks. Swift version

ContainerController UI Component. This is a copy swipe-panel from app: https://www.apple.com/ios/maps/ Preview Requirements Installation CocoaPods Swi

A message bar for iOS written in Swift.
A message bar for iOS written in Swift.

Dodo, a message bar for iOS / Swift This is a UI widget for showing text messages in iOS apps. It is useful for showing short messages to the user, so

Protocol oriented, type safe, scalable design system foundation swift framework for iOS.
Protocol oriented, type safe, scalable design system foundation swift framework for iOS.

Doric: Design System Foundation Design System foundation written in Swift. Protocol oriented, type safe, scalable framework for iOS. Features Requirem

Cool Animated music indicator view written in Swift
Cool Animated music indicator view written in Swift

Cool Animated music indicator view written in Swift. ESTMusicIndicator is an implementation of NAKPlaybackIndicatorView in Swift for iOS 8. 本人著作的书籍《La

Comments
  • Support both dynamic and static linking

    Support both dynamic and static linking

    Xcode unfortunately seems to always opt-into statically linking swift modules. However many times you'd like to instead use a module from within a Framework. Since frameworks on iOS cannot bundle modules / frameworks of their own, the only option is to use dynamic linking and bundle the module separately with the app.

    This pull request adds a separate target for static linking.

    opened by guidedways 1
Owner
Darren Ford
Darren Ford
A framework which helps you attach observers to `UIView`s to get updates on its frame changes

FrameObserver is a framework that lets you attach observers to any UIView subclass and get notified when its size changes. It doesn't use any Method S

null 11 Jul 25, 2022
Catalyst example using an AppKit-provided NSVisualEffectView to provide a translucent blurred window

CatalystEffectViewChrome This project demonstrates how to insert an NSVisualEffe

Steven Troughton-Smith 68 Aug 11, 2022
:octocat:💧 A slider widget with a popup bubble displaying the precise value selected. Swift UI library made by @Ramotion

FLUID SLIDER A slider widget with a popup bubble displaying the precise value selected written on Swift. We specialize in the designing and coding of

Ramotion 1.9k Dec 23, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle.

Twinkle ✨ Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle. This library creates several CAEmitterLayers and animate

patrick piemonte 600 Nov 24, 2022
Simple battery shaped UIView

BatteryView Simple battery shaped UIView. Usage let batteryView = BatteryView(frame: smallRect) batteryView.level = 42 // anywhere in 0...100 batteryV

Yonat Sharon 50 Sep 19, 2022
Elissa displays a notification on top of a UITabBarItem or any UIView anchor view to reveal additional information.

Elissa Attach a local notification to any UIView to reveal additional user guidance. Usage Example Per default, Elissa will try to align to the center

null 169 Aug 14, 2022
An iOS Library that makes shadows management easy on UIView.

ShadowView is an iOS Shadow library that makes view's shadow implementation easy and sweet ?? ?? . Add simple shadows to add a gaussian blurred projec

Pierre 404 Dec 8, 2022
High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton, Promise and more.

SwiftyUI High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton and more. Features SwiftyView GPU rendering Image and Color

Haoking 336 Nov 26, 2022
Custom Beautiful UIView For Handling IDs in iOS

IDView Custom Beautiful UIView For Handling IDs in iOS Setup Set the placeholder images for the front and back faces. override func viewDidLoad()

Omar Labib 6 Aug 21, 2021