SwiftUI How to vertically center a view inside a VStack - swiftui

I would like to have one view in the vertical center of the screen, one view at the top of the screen and one view vertically centered between these two views like so:
This took me 5min to do on a storyboard but I don't seem to find a way to do it in SwiftUI 🙃.
I already tried with multiple zstacks, vstacks, multiple custom alignments but this is the closest I got:
struct SelectionView: View {
var body: some View {
ZStack(alignment: .myAlignment) {
Color.green
.edgesIgnoringSafeArea(.all)
VStack {
Image(systemName: "clock")
.resizable()
.foregroundColor(.white)
.aspectRatio(contentMode: .fit)
.frame(width: 156, height: 80)
// Spacer()
Text("My\nmultiline label")
.multilineTextAlignment(.center)
.font(.title)
.foregroundColor(.white)
// Spacer()
VStack(spacing: 16) {
RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
}
.alignmentGuide(VerticalAlignment.myAlignment) { dimension in
dimension[VerticalAlignment.center]
}
.layoutPriority(1)
}
.padding([.leading, .trailing], 24)
}
}
}
struct SelectionView_Previews: PreviewProvider {
static var previews: some View {
LanguageSelectionView()
}
}
// MARK
extension HorizontalAlignment {
enum MyHorizontal: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat
{ d[HorizontalAlignment.center] }
}
static let myAlignment =
HorizontalAlignment(MyHorizontal.self)
}
extension VerticalAlignment {
enum MyVertical: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat
{ d[VerticalAlignment.center] }
}
static let myAlignment = VerticalAlignment(MyVertical.self)
}
extension Alignment {
static let myAlignment = Alignment(horizontal: .myAlignment,
vertical: .myAlignment)
}
I'm keeping the GeometryReader as a last resort as it feels like a too drastic measure for this seemingly simple layout..
I guess I'm approaching this in some wrong way (still too much UIKit/Constraints in my head)..

Here is possible solution. Tested with Xcode 12 / iOS 14
struct SelectionView: View {
var body: some View {
ZStack {
Color.green
.edgesIgnoringSafeArea(.all)
VStack(spacing: 16) {
Color.clear
.overlay(
VStack {
Image(systemName: "clock")
.resizable()
.foregroundColor(.white)
.aspectRatio(contentMode: .fit)
.frame(width: 156, height: 80)
Color.clear
.overlay(
Text("My\nmultiline label")
.multilineTextAlignment(.center)
.font(.title)
.foregroundColor(.white)
)
}
)
RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
Color.clear
}
.padding([.leading, .trailing], 24)
}
}
}

Related

Why is the button in the body behaving differently than the button in my NavigationView toolbar?

I don't really follow why the following button:
Button { } label: {
Image(systemName: "globe")
.resizable()
.scaledToFill()
}
.frame(width: size, height: size)
.border(.yellow)
is behaving differently in the body and in the NavigationView?
Why isn't the one in the NavigationView filling the entire frame?
struct ContentView: View {
let size = 45.0
let fontSize = 17.0
var body: some View {
NavigationView {
Button { } label: {
Image(systemName: "globe")
.resizable()
.scaledToFill()
}
.frame(width: size, height: size)
.border(.yellow)
.toolbar {
HStack(alignment: .top) {
Button { } label: {
Image(systemName: "globe")
.resizable()
.scaledToFill()
}
.frame(width: size, height: size)
.border(.red)
// Image and Title
VStack {
Image("nemo")
.resizable()
.scaledToFit()
.frame(height: size)
Text("Navigation Title")
.font(.system(size: fontSize))
.bold()
}.border(.green)
}
//.frame(maxWidth: .infinity)
}
}
}
}
This is a design of default button in toolbar, instead we can use custom, like
Button { print(">> action here")} label: {
Image(systemName: "globe")
.resizable()
.scaledToFill()
}
.buttonStyle(MyTabbarButtonStyle())
.frame(width: size, height: size)
.border(.red)
// and style (tune colours as you want)
struct MyTabbarButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundColor(configuration.isPressed ? .gray : .blue)
}
}

Scrollable content not working as expected in SwiftUI

I'm trying to create a scroll view with my custom view, but when I add scroll to view it's not working as expected, without scroll view working fine.
struct ContentView: View {
var body: some View {
ScrollView(.vertical) {
VStack {
ForEach (0..<2) { _ in
ListItem()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// But the below code is working fine.
struct ContentView: View {
var body: some View {
VStack {
ForEach (0..<2) { _ in
ListItem()
}
}
}
}
// List Item
struct ListItem: View {
var body: some View {
VStack {
HStack {
Image("steve")
.resizable()
.clipShape(Circle())
.aspectRatio(contentMode: .fit)
.frame(maxWidth:44, maxHeight: 44)
VStack {
Text("Steve Jobs")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
Text("1 hour ago")
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
Spacer()
}
ZStack(alignment:.top) {
GeometryReader { geometry in
VStack {
ZStack {
Image("poster_1")
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(8)
.shadow(color: Color.black.opacity(0.12),
radius: 4, x: 1, y: 1)
.frame(width: geometry.size.width - 64,
height: geometry.size.height * 0.35)
.padding([.horizontal], 32)
.clipped()
ZStack {
Rectangle()
.fill(Color.black.opacity(0.75))
.frame(maxWidth:84 , maxHeight: 84)
.cornerRadius(12)
Image(systemName: "play.fill")
.font(.system(size: 44, weight: .bold))
.foregroundColor(.white)
}
}
VStack {
Text("Game of Thrones")
.accentColor(Color.gray.opacity(0.25))
.font(Font.subheadline.weight(.bold))
.padding([.horizontal], 32)
.padding([.bottom], 2)
.frame(maxWidth: .infinity,
alignment: .leading)
VStack {
Text("Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. ")
.accentColor(Color.gray.opacity(0.25))
.font(.footnote)
.frame(maxWidth: .infinity,
alignment: .leading)
.padding([.horizontal], 32)
Text("Show more...")
.accentColor(Color.gray.opacity(0.01))
.font(Font.footnote.weight(.bold))
.frame(maxWidth: .infinity,
alignment: .trailing)
.padding([.trailing], 32).onTapGesture {
print("okay")
}
}
}
}
}
}
}
}
}
ListItem contains multiple views which creates publisher info and movie information as shown below image.
Scrollview is scrolling but images are not shown in view as first image.
It is the geometry reader that you have in ListItem. Because neither a GeometryReader nor a Scrollview have their own size. Since neither no what size to render, they collapse. This is what you are seeing in your view. See this answer. The solution is to put the GeometryReader into ContentView outside the Scrollview and send the GeometryProxy that you called geometry into ListItem something like this:
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
ScrollView(.vertical) {
VStack {
ForEach (0..<2) { _ in
ListItem(geometry: geometry)
}
}
} // Scrollview
} // GeometryReader
}
}
struct ListItem: View {
let geometry: GeometryProxy
var body: some View {
...
}
This seems to fix it in Preview, though you may have to change your multipliers in the .frame() that uses geometry to size it how you want.

Animated shutter button like in the camera app in SwiftUI

How can you build something like the animated shutter button in the camera app in SwiftUI?
// SwiftUIPlayground
// https://github.com/ralfebert/SwiftUIPlayground/
import SwiftUI
struct CameraButtonView: View {
#State var recording = false
var action: ((_ recording: Bool) -> Void)?
var body: some View {
ZStack {
Circle()
.stroke(lineWidth: 6)
.foregroundColor(.white)
.frame(width: 65, height: 65)
RoundedRectangle(cornerRadius: recording ? 8 : self.innerCircleWidth / 2)
.foregroundColor(.white)
.frame(width: self.innerCircleWidth, height: self.innerCircleWidth)
}
.animation(.linear(duration: 0.2))
.padding(20)
.onTapGesture {
withAnimation {
self.recording.toggle()
self.action?(self.recording)
}
}
}
var innerCircleWidth: CGFloat {
self.recording ? 32 : 55
}
}
struct CameraButtonView_Previews: PreviewProvider {
static var previews: some View {
Group {
CameraButtonView(recording: false)
.previewLayout(PreviewLayout.sizeThatFits)
.previewDisplayName("not recording")
.background(Color.gray)
CameraButtonView(recording: true)
.previewLayout(PreviewLayout.sizeThatFits)
.previewDisplayName("recording")
.background(Color.gray)
ZStack {
Image("turtlerock")
.resizable()
.aspectRatio(contentMode: .fit)
HStack {
Spacer()
CameraButtonView()
}
}
}
}
}

SwiftUI GeometryReader compact size

I would like my LoadingTitle to have a width of 70% of the screen so I use the GeometryReader but it makes the vertical size expand and my LoadingTitle takes much more vertical space. I would like it to remain as compact as possible.
When using hardcoded width: 300 I get the correct layout (except the relative width):
struct ContentView: View {
var body: some View {
VStack(alignment: .leading, spacing: 0) {
LoadingTitle()
Color.blue
}
}
}
struct LoadingTitle: View {
var body: some View {
HStack() {
Color.gray
}
.frame(width: 300, height: 22)
.padding(.vertical, 20)
.border(Color.gray, width: 1)
}
}
Now if I wrap the body of my LoadingTitle in the GeometryReader I can get the correct relative size but then the GeometryReader expands my view vertically:
struct LoadingTitle: View {
var body: some View {
GeometryReader { geo in
HStack() {
Color.gray
.frame(width: geo.size.width * 0.7, height: 22, alignment: .leading)
Spacer()
}
.padding(.vertical, 20)
.border(Color.gray, width: 1)
}
}
}
I tried using .fixedSize(horizontal: false, vertical: true) on the GeometryReader as other suggested but then the resulting view is too much compact and all its paddings are ignored:
How could I achieve the layout of the 1st screenshot with a relative width?
Here is possible approach. Tested with Xcode 11.4 / iOS 13.4 (w/ ContentView unchanged)
struct LoadingTitle: View {
var body: some View {
VStack { Color.clear }
.frame(height: 22).frame(maxWidth: .infinity)
.padding(.vertical, 20)
.overlay(
GeometryReader { geo in
HStack {
HStack {
Color.gray
.frame(width: geo.size.width * 0.7, height: 22)
}
.padding(.vertical, 20)
.border(Color.gray, width: 1)
Spacer()
}
}
)
}
}
Since you have a fixed height for title,
struct LoadingTitle1: View {
var body: some View {
GeometryReader { geo in
HStack {
Color.gray.frame(width: geo.size.width * 0.7)
.padding(.vertical, 20)
.border(Color.gray, width: 1)
Spacer()
}
}.frame(height: 62)
}
}

SwiftUI - Tapping a Button changes VStack's background color

When I tapped OrderButton, all the VStack's background color is changing to gray color then turning back like assigned a click event. How can I prevent this?
import SwiftUI
struct DrinkDetail : View {
var drink: Drink
var body: some View {
List {
ZStack (alignment: .bottom) {
Image(drink.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
Rectangle()
.frame(height: 80)
.opacity(0.25)
.blur(radius: 10)
HStack {
VStack(alignment: .leading, spacing: 3) {
Text(drink.name)
.foregroundColor(.white)
.font(.largeTitle)
Text("It is just for $5.")
.foregroundColor(.white)
.font(.subheadline)
}
.padding(.leading)
.padding(.bottom)
Spacer()
}
}
.listRowInsets(EdgeInsets())
VStack(alignment: .leading) {
Text(drink.description)
.foregroundColor(.primary)
.font(.body)
.lineLimit(nil)
.lineSpacing(12)
HStack {
Spacer()
OrderButton()
Spacer()
}
.padding(.top, 50)
.padding(.bottom, 50)
}
.padding(.top)
}
.edgesIgnoringSafeArea(.top)
.navigationBarHidden(true)
}
}
struct OrderButton : View {
var body: some View {
Button(action: {}) {
Text("Order Now")
}
.frame(width: 200, height: 50)
.foregroundColor(.white)
.font(.headline)
.background(Color.blue)
.cornerRadius(10)
}
}
#if DEBUG
struct DrinkDetail_Previews : PreviewProvider {
static var previews: some View {
DrinkDetail(drink: LoadModule.sharedInstance.drinkData[3])
}
}
#endif
The issue resolved by using ScrollView and adding some more parameters for auto resize of Text:
ScrollView(.vertical, showsIndicators: false) {
ZStack (alignment: .bottom) {
Image(drink.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
Rectangle()
.frame(height: 80)
.opacity(0.25)
.blur(radius: 10)
HStack {
VStack(alignment: .leading, spacing: 3) {
Text(drink.name)
.foregroundColor(.white)
.font(.largeTitle)
Text("It is just for $5.")
.foregroundColor(.white)
.font(.subheadline)
}
.padding(.leading)
.padding(.bottom)
Spacer()
}
}
.listRowInsets(EdgeInsets())
VStack(alignment: .leading) {
Text(drink.description)
.foregroundColor(.primary)
.font(.body)
.lineLimit(nil)
.fixedSize(horizontal: false, vertical: true)
.lineSpacing(12)
.padding(Edge.Set.leading, 15)
.padding(Edge.Set.trailing, 15)
HStack {
Spacer()
OrderButton()
Spacer()
}
.padding(.top, 50)
.padding(.bottom, 50)
}
.padding(.top)
}
.edgesIgnoringSafeArea(.top)
.navigationBarHidden(true)
What's the UI you are trying to get? Because, from your example, it seems that List is not necessary. Indeed, List is:
A container that presents rows of data arranged in a single column.
If you don't really need List you can replace it with VStack (if your content must fit the screen) or with a ScrollView (if your content is higher than the screen). Replacing the List will solve your issue that depends on the list selection style of its cells.
An alternative, if you need to use the List view is to set the selection style of the cells in the SceneDelegate to none (but this will affect all of your List in the project) this way:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView() //replace this with your view
if let windowScene = scene as? UIWindowScene {
UITableViewCell.appearance().selectionStyle = .none
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}