SwiftLint
SwiftLint copied to clipboard
Rule Request: SwiftUI: Prefer scaledToFit()/scaledToFill() over aspectRatio(contentMode:)
New Issue Checklist
- [x] Updated SwiftLint to the latest version
- [x] I searched for existing GitHub issues
New rule request
SwiftUI has scaledToFit() scaledToFill() which are convenience methods for calling aspectRatio with only a content mode.
This method is equivalent to calling aspectRatio(_:contentMode:) with a nil aspectRatio and a content mode of ContentMode.fit. https://developer.apple.com/documentation/swiftui/view/scaledtofit()#
Since Apple considered it a common enough use case to have dedicated view modifiers for it, there should be a rule to prefer using them over the more general purpose view modifier.
Triggering cases
It just needs to be the versions where they're passed a constant.
view.aspectRatio(contentMode: .fit)
view.aspectRatio(contentMode: .fill)
aspectRatio(contentMode: .fit)
aspectRatio(contentMode: .fill)
Non-triggering cases
If a ratio is being passed or the content mode is not a constant, it should not trigger
let ratio = CGSize(width: 1, height: 1)
view.aspectRatio(ratio, contentMode: .fit)
view.aspectRatio(ratio, contentMode: .fill)
let contentMode = ContentMode.fit
view.aspectRatio(contentMode: contentMode)
let shouldFit = true
view.aspectRatio(contentMode: shouldFit ? .fit : .fill)
Configuration
I don't think this needs any configuration.
It's always possible someone else would prefer the aspectRatio method over the convenience method. If that occurs the rule could be modified to controlling the preferred method, though it could also be a separate rule as well since it would be checking for the opposite case.
Opt-in?
Based on the criteria in the readme, this could be enabled by default. Though it depends on what the general consensus is.
@CraigSiemens please assign this issue to me.
@CraigSiemens please assign this issue to me.
Done. Please go ahead. I'm happy to review your pull request once you're done.