Skip to content

Rule Request: SwiftUI: Prefer scaledToFit()/scaledToFill() over aspectRatio(contentMode:) #5713

@CraigSiemens

Description

@CraigSiemens

New Issue Checklist

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.

Metadata

Metadata

Assignees

Labels

good first issueIssue to be taken up by new contributors yet unfamiliar with the project.rule-requestRequests for a new rules.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions