Change width of Picker view in SwiftUI
Say we need to show two Picker
views horizontally with specified width
. We can simply set frame
with width
value 150
for each of the Picker
as follows -
You will notice that setting frame
on Picker
didn’t work properly.
On our HStack
, we had spacing
value of 30
, but the views overlap. As a result, the touch area overlaps (we can scroll through right side Picker values from within the area of left side Picker).
By using the .clipped()
modifier to both Picker
views, we can solve the visual overlap between the views.
We can see the views are within their specified width
and there is a horizontal spacing between them. We can also expect that the scrolling issue is fixed as well. Let’s try again.
We can see the issue with touch overlap is still there.
To fix the issue, let’s add the following UIPickerView
extension -
Under the hood, SwiftUI Picker
view uses UIKit UIPickerView
component. Here we override the intrinsicContentSize
property and set width
value to UIView.noIntrinsicMetric
.
Let’s run the app again.
This time touch areas for two Picker
views no longer overlap.
Thanks for reading our blog. Please share your thoughts and suggestions on this article.
Keep up with us on social media:
LinkedIn: https://www.linkedin.com/company/evangelist-apps-limited/
Twitter: https://twitter.com/EvangelistSW/