Aligning Text within ZStack based on rotation in SwiftUI - text

I'm having some trouble aligning Text inside a ZStack...more specifically, if I rotate the device after I started the app...
I want the Text to be aligned to the top leading of the View, but below you can see images of what's happening...
If I open the app with the device in portrait, the alignment is correct...
Alignment with app started in portrait
...but if I rotate the device to landscape, the text moves to the top center...
Alignment after rotation to landscape
Same thing if I start the app with the device in landscape, all aligned correctly...
Alignment with app started in landscape
...but if I rotate the device to portrait, the text almost disappear completely...
Alignment after rotation to portrait
This is the code for the ContentView:
import SwiftUI
let furl = URL(fileURLWithPath: "path")
struct ContentView: View {
#State private var selected = 0
var body: some View {
TabView(selection: $selected) {
NavigationView {
HomeView()
}
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 0 ? "house.fill" : "house"))
Text("Home")
}.tag(0)
NavigationView {
CategoryView(dm: DownloadManager())
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 1 ? "text.justify" : "text.justify"))
Text("Categorie")
}.tag(1)
NavigationView {
GalleryView(dm: DownloadManager())
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 2 ? "photo.fill" : "photo"))
Text("Galleria")
}.tag(2)
NavigationView {
FavoritesView()
}
.navigationViewStyle(DoubleColumnNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 3 ? "star.fill" : "star"))
Text("Preferiti")
}.tag(3)
NavigationView {
InfoView()
}
.navigationViewStyle(StackNavigationViewStyle())
.tabItem {
Image(systemName: (selected == 4 ? "info.circle.fill" : "info.circle"))
Text("Informazioni")
}.tag(4)
}
.accentColor(.white)
.onAppear() {
UINavigationBar.appearance().barTintColor = UIColor(red: 112.0/255.0, green: 90.0/255.0, blue: 143.0/255.0, alpha: 1.0)
UITabBar.appearance().barTintColor = UIColor(red: 112.0/255.0, green: 90.0/255.0, blue: 143.0/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This is the code for the HomeView (where I have the problem):
import SwiftUI
struct HomeView: View {
#State private var showAlertSheet = false
#ObservedObject var monitor = NetworkMonitor()
var body: some View {
ZStack {
Image("vivibusso_home")
.resizable()
.aspectRatio(contentMode: .fill)
.clipped()
VStack(alignment: .leading) {
Text("Benvenuto")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
Text("a Busso!")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
}
.frame(maxWidth: UIScreen.main.bounds.width, maxHeight: UIScreen.main.bounds.height, alignment: .topLeading)
.padding(.top)
}
.navigationTitle(Text("ViviBusso"))
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing:
Button (action: {
self.showAlertSheet = true
}) {
Image(systemName: monitor.isConnected ? "wifi" : "wifi.slash")
})
.alert(isPresented: $showAlertSheet) {
if monitor.isConnected {
return Alert(title: Text("Tutto OK!"), message: Text("ViviBusso funziona correttamente!"), dismissButton: .default(Text("OK")))
}
return Alert(title: Text("Attenzione!"), message: Text("ViviBusso ha bisogno della connessione Internet per funzionare!"), dismissButton: .default(Text("OK")))
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
How can I solve this?
Thank you!

ZStack(alignment:.topLeading) { //<= here
GeometryReader { proxy in //<= here
Image("vivibusso_home")
.resizable()
.aspectRatio(contentMode: .fill)
.border(Color.black)
.frame(width: proxy.size.width, height: proxy.size.height)// <= here
}
VStack(alignment: .leading) {
Text("Benvenuto")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
Text("a Busso!")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading)
}
//<=here
.padding(.top)
}
.navigationTitle(Text("ViviBusso"))
...

Related

How can I solve "No exact matches in call to initializer" error when I am using Text in SwiftUI?

I just started with SwiftUI and have basic questions.
I try to show the value of the rotation in the Text field. The error message I get is: "No exact matches in call to initializer"
Where is the mistake?
import SwiftUI
struct ContentView: View {
#State var rotation: Double = 0
var body: some View {
VStack {
VStack {
Text("Hello, world!")
.padding()
Slider(value: $rotation, in: 0 ... 360, step: 0.1)
.padding()
Text(rotation)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
and for fun you can also try this:
struct ContentView: View {
#State var rotation: Double = 0
var body: some View {
VStack {
Text("Hello, world!").rotationEffect(Angle(degrees: rotation)).padding()
Slider(value: $rotation, in: 0 ... 360, step: 0.1).padding()
Text("\(rotation)")
}
}
}
You should return a String type for initialization of Text, like this:
struct ContentView: View {
#State var rotation: Double = 0
var body: some View {
VStack {
VStack {
Text("Hello, world!")
.padding()
Slider(value: $rotation, in: 0 ... 360, step: 0.1)
.padding()
Text(rotation.string)
}
}
}
}
extension CustomStringConvertible { var string: String { get { return String(describing: self) } } }

Struggling with layout in SwiftUI on TVOS

I have a workable UI in TVOS using SwiftUI, but I can't figure out how to make it lay out properly.
Goals:
Screen is full screen, not inset in safe area
Album image is square, aspect ratio preserved, fills top-to-bottom
Album and artist text lays out comfortably, near the album art
import SwiftUI
struct ContentView: View {
#ObservedObject var ds = DataStore()
var body: some View {
HStack(alignment: .top) {
if (ds.currentRoom.albumImage != nil) {
Image(uiImage: ds.currentRoom.albumImage!)
.resizable()
.aspectRatio(contentMode: ContentMode.fit)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.black)
}
VStack(alignment: .leading, spacing: 8) {
Text(ds.currentRoom.artist ?? "?")
.font(.system(.title, design: .default))
.bold()
.foregroundColor(Color.gray)
.padding(.top, 100)
Text(ds.currentRoom.title ?? "?")
.font(.system(.headline, design: .default))
.foregroundColor(Color.gray)
.padding(.bottom, 100)
Button(action: { print ("pressed!" )} ) {
Image(systemName: "playpause")
.font(.system(.title, design: .default))
.foregroundColor(Color.gray)
.padding(30)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.green, lineWidth: 4)
)
}
}
}
.padding(20)
.background(Color.black)
.edgesIgnoringSafeArea(.all)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
In case it helps, here are the relevant helper and DataSource methods:
The DataStore() class has this method:
import SwiftUI
import Combine
class CurrentRoom {
var artist: String?
var title: String?
var album: String?
var albumArtURI: String?
var absoluteAlbumArtURI: String?
var albumImage: UIImage?
}
class DataStore: ObservableObject {
#Published var currentRoom: CurrentRoom = CurrentRoom()
init() {
getCurrentRoom()
}
func getCurrentRoom() {
currentRoom.artist = "Eilen Jewell"
currentRoom.album = "Sundown over Ghost Town"
currentRoom.title = "Half-Broke Horse"
currentRoom.absoluteAlbumArtURI = "https://images-na.ssl-images-amazon.com/images/I/71mkKfTQD0L._SX425_.jpg"
currentRoom.albumImage = Api().getImageDataFromURI(UrlAsString: currentRoom.absoluteAlbumArtURI)
}
}
struct DataStore_Previews: PreviewProvider {
static var previews: some View {
/*#START_MENU_TOKEN#*/Text("Hello, World!")/*#END_MENU_TOKEN#*/
}
}
Finally:
class Api {
func getImageDataFromURI(UrlAsString: String?) -> UIImage? {
if let URI = UrlAsString {
if URI.starts(with: "http") {
if let url = URL(string: URI) {
let data = try? Data(contentsOf: url)
if let imageData = data {
return UIImage(data: imageData)
}
}
}
}
return nil
}
}
Goal:
You can either go with Asperis answer, or, if ContentMode.Fit is important to you (as you don't want to clip the image), just remove the width part of the frame modifier at your Image, and then add a Spacer behind the VStack, which will consume the rest:
struct ContentView: View {
#ObservedObject var ds = DataStore()
var body: some View {
HStack(alignment: .top) {
if (ds.currentRoom.albumImage != nil) {
Image(uiImage: ds.currentRoom.albumImage!)
.resizable()
.aspectRatio(contentMode: ContentMode.fit)
.frame(minHeight: 0, maxHeight: .infinity)
.background(Color.black)
}
VStack(alignment: .leading, spacing: 8) {
Text(ds.currentRoom.artist ?? "?")
.font(.system(.title, design: .default))
.bold()
.foregroundColor(Color.gray)
.padding(.top, 100)
Text(ds.currentRoom.title ?? "?")
.font(.system(.headline, design: .default))
.foregroundColor(Color.gray)
.padding(.bottom, 100)
Button(action: { print ("pressed!" )} ) {
Image(systemName: "playpause")
.font(.system(.title, design: .default))
.foregroundColor(Color.gray)
.padding(30)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.green, lineWidth: 4)
)
}
}
.padding(.leading, 10)
Spacer()
}
.padding(20)
.background(Color.black)
.edgesIgnoringSafeArea(.all)
}
}
This will result in this image:
Correct layout

SwiftUI layout grows outside the bounds of the device when using .edgesIgnoringSafeArea()

Having an issue in SwiftUI where some Views are growing bigger vertically than the size of the device when using .edgesIgnoringSafeArea(.bottom). On an iPhone 11 Pro which is 812 pixels high I am seeing a view of size 846. I am using the Debug View Hierarchy to verify it. This has been tested on Xcode 11.4.1 and 11.1 and exists in both versions and probably all in between.
I have included sample code below.
I am pretty sure this is a SwiftUI bug, but was wondering if anyone has a workaround for it. I need the edgesIgnoringSafeArea(.bottom) code to draw the TabBar, and for the ProfileView() to extend to the bottom of the screen when I hide my custom tab bar.
struct ContentView: View {
var body: some View {
MainTabView()
}
}
struct MainTabView : View {
enum Item : CaseIterable {
case home
case resources
case profile
}
#State private var selected : Item = .home
var body: some View {
VStack(spacing: 0.0) {
ZStack {
HomeView()
.zIndex(selected == .home ? 1 : 0)
ResourcesView()
.zIndex(selected == .resources ? 1 : 0)
ProfileView()
.zIndex(selected == .profile ? 1 : 0)
}
// Code here for building and showing/hiding a Toolbar
// Basically just a HStack with a few buttons in it
}
.edgesIgnoringSafeArea(.bottom) // <- This causes the screen to jump to 846
}
}
struct ProfileView : View {
#State private var showQuestionnaireView = false
var body: some View {
NavigationView {
ZStack {
NavigationLink(destination: QuestionnaireView( showQuestionnaireView:$showQuestionnaireView),
isActive: $showQuestionnaireView) {
Text("Show Questionnaire View")
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
}
struct QuestionnaireView : View {
#Binding var showQuestionnaireView : Bool
var body: some View {
GeometryReader { screenGeometry in
ZStack {
Color.orange
VStack {
Text("Top")
Spacer()
Text("Bottom")
}
}
}
}
}
HomeView() and ResourcesView() are just copies of ProfileView() that do their own thing.
When you run it you will see a button, push the button and a hidden Navigation Stack View pushes on the QuestionnaireView, this view contains a VStack with two text fields, neither of which you will be able to see due to this issue. Understandably the top one is behind the notch, but the bottom one is off the bottom of the screen. In my real project this issue is rarely seen at runtime, but switching between dark mode and light mode shows it. In the above code there is no need to switch appearances.
EDIT: FB7677794 for anyone interested, have not received any updates from Apple since lodging it 3 weeks ago.
EDIT2: Added some more code to MainTabBar
Update: This is fixed in Xcode 12 Beta 2
After reading the updated question I have made some changes and tried to make a small demo. In this, I am using the same approach as before, put NavigationView in your main tab view and with this you don't have to hide and show every time you come or leave your main tab view.
import SwiftUI
struct ContentView: View {
var body: some View {
MainTabView()
}
}
struct MainTabView : View {
enum Item : CaseIterable {
case home
case resources
case profile
}
#State private var selected : Item = .home
var body: some View {
NavigationView {
VStack(spacing: 0.0) {
ZStack {
Group {
HomeView()
.zIndex(selected == .home ? 1 : 0)
ResourcesView()
.zIndex(selected == .resources ? 1 : 0)
ProfileView()
.zIndex(selected == .profile ? 1 : 0)
}
.frame(minWidth: .zero, maxWidth: .infinity, minHeight: .zero, maxHeight: .infinity)
.background(Color.white)
}
HStack {
Group {
Image(systemName: "house.fill")
.onTapGesture {
self.selected = .home
}
Spacer()
Image(systemName: "plus.app.fill")
.onTapGesture {
self.selected = .resources
}
Spacer()
Image(systemName: "questionmark.square.fill")
.onTapGesture {
self.selected = .profile
}
}
.padding(.horizontal, 30)
}
.frame(height: 40)
.foregroundColor(Color.white)
.background(Color.gray)
// Code here for building and showing/hiding a Toolbar
// Basically just a HStack with a few buttons in it
}
.edgesIgnoringSafeArea(.bottom)
} // <- This causes the screen to jump to 846
}
}
struct ProfileView : View {
#State private var showQuestionnaireView = false
var body: some View {
// NavigationView {
ZStack {
NavigationLink(destination: QuestionnaireView( showQuestionnaireView:$showQuestionnaireView),
isActive: $showQuestionnaireView) {
Text("Show Questionnaire View")
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
// }
}
}
struct QuestionnaireView : View {
#Binding var showQuestionnaireView : Bool
var body: some View {
GeometryReader { screenGeometry in
ZStack {
Color.orange
VStack {
Text("Top")
Spacer()
Text("Bottom")
}
}
.edgesIgnoringSafeArea(.bottom)
}
}
}
struct HomeView: View {
var body: some View {
NavigationLink(destination: SecondView()) {
Text("Home View")
}
}
}
struct ResourcesView: View {
var body: some View {
NavigationLink(destination: SecondView()) {
Text("Resources View")
}
}
}
struct SecondView: View {
var body: some View {
Text("Second view in navigation")
.background(Color.black)
.foregroundColor(.white)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice(PreviewDevice(rawValue: "iPhone 11"))
}
}
It is due to undefined size for NavigationView. When you add your custom tab bar component, as in example below, that limits bottom area, the NavigationView will layout correctly.
Tested with Xcode 11.4 / iOS 13.4
struct MainTabView : View {
var body: some View {
VStack(spacing: 0.0) {
ZStack {
Color(.cyan)
ProfileView() // << this injects NavigationView
}
HStack { // custom tab bar
Button(action: {}) { Image(systemName: "1.circle").padding() }
Button(action: {}) { Image(systemName: "2.circle").padding() }
Button(action: {}) { Image(systemName: "3.circle").padding() }
}.padding(.bottom)
}
.edgesIgnoringSafeArea(.bottom) // works !!
}
}

Same image being shown when showing a modal via .sheet after iterating array

In a swiftui app, I am iterating an array of entities and showing thumbmnail images and have it set up that when one is tapped, a detail view is shown with that particular full size image. The problem is that it's always the most recent image being shown when going to the detail screen.
Main view:
if documents.count > 0 {
ScrollView(.horizontal, showsIndicators: true) {
HStack {
ForEach(documents, id: \.self.id) {(doc: Document) in
Image(uiImage: UIImage(data: doc.image)!)
.resizable()
.frame(width: 40, height: 50, alignment: .center)
.clipShape(Rectangle())
.cornerRadius(8)
.scaledToFit()
.onTapGesture {
self.showImageDetail = true
}
.padding(.all, 5)
.sheet(isPresented: self.$showImageDetail, content: {
ImageViewDetail(image: UIImage(data: doc.image)!)
})
}
}
}
}
When ImageDetailView is shown, it's alway the most recent image saved. Below is the detail view code:
import SwiftUI
struct ImageViewDetail: View {
#Environment(\.presentationMode) var presentationMode
#State var image: UIImage
#State var scale: CGFloat = 1.0
var body: some View {
VStack {
Image(uiImage: image)
.resizable()
.padding()
.scaledToFit()
.scaleEffect(scale)
.cornerRadius(8)
.gesture(MagnificationGesture()
.onChanged {value in
self.scale = value.magnitude
}
)
HStack {
Button("Back") {
self.presentationMode.wrappedValue.dismiss()
}
.buttonStyle(FillStyle(width: 86, height: 32))
.padding(.trailing, 10)
Button("Delete") {
}
.buttonStyle(FillStyle(width: 86, height: 32))
.padding(.leading, 10)
}
}
.navigationBarTitle("Image", displayMode: .inline)
}
}
Any help would be greatly appreciated - I can't seem to see why the right image is not displayed by the ImageDetailView? Many thanks in advance.
Replace the Bool state with a Document? state:
#State var selectedDocument: Document?
var body: some View {
HStack {
ForEach(documents, id: \.self.id) {(doc: Document) in
Image(uiImage: UIImage(data: doc.image)!)
.onTapGesture {
self.selectedDocument = doc
}
}
}
}
.sheet(item: $selectedDocument) {
ImageViewDetail(image: UIImage(data: $0.image)!)
}
}
Sheet can be only one in view hierarchy, so below it is relocated for HStack and it is needed to add member currentImage
Here is scratchy approach... (not tested - might be needed take care of optionals)
#State private var currentImage: UIImage = UIImage() // < needed optionals?
...
ScrollView(.horizontal, showsIndicators: true) {
HStack {
ForEach(documents, id: \.self.id) {(doc: Document) in
Image(uiImage: UIImage(data: doc.image)!)
.resizable()
.frame(width: 40, height: 50, alignment: .center)
.clipShape(Rectangle())
.cornerRadius(8)
.scaledToFit()
.onTapGesture {
self.currentImage = UIImage(data: doc.image) ?? UIImage() // < current
self.showImageDetail = true
}
.padding(.all, 5)
}
}
.sheet(isPresented: self.$showImageDetail, content: { // < one sheet
ImageViewDetail(image: self.currentImage)
})
}

SwiftUI: VStack don't apply to white background color but every other color

I have following code. If I change .background(Color.green) to .background(Color.white) for the VStack the background will be the systemGray I used for the Listbackground.
Has it something to do with the .colorMultiply(Color(UIColor.systemGray4)) property?.
var body: some View {
NavigationView {
List {
Text("Bla bla bla")
Group {
VStack {
TextField("Server address", text: $serverAddress)
.keyboardType(.default)
TextField("Server port", text: $serverPortString)
.keyboardType(.numberPad)
}
}
.padding()
.background(Color.green)
.cornerRadius(8)
// Some more elements
}
.navigationBarHidden(false)
.navigationBarTitle("Connect your Server", displayMode: .large)
}
.colorMultiply(Color(UIColor.systemGray4))
.onTapGesture {
self.hideKeyboard()
}
White background that get ignored:
Working green background:
.colorMultiply() adds a color multiplication effect to the view that it is applied on, meaning that it tints it the color that you have added. As your NavigationView is the containing view, all views inside it will be tinted systemGray4.
When you set it to white, the systemGray4 tints that so that it blends in with the background as that is also white.
You could do something like this:
struct ContentView: View {
#State var serverAddress: String = ""
#State var serverPortString: String = ""
let backgroundColor = Color.init(UIColor.systemGray4)
init() {
UITableView.appearance().backgroundColor = .clear // or you could set this to systemGray4 and ignore the ZStack
UITableView.appearance().separatorColor = .clear
UITableView.appearance().tableFooterView = UIView()
UITableView.appearance().separatorStyle = .none
}
var body: some View {
NavigationView {
ZStack {
backgroundColor.frame(maxWidth: .infinity, maxHeight: .infinity).edgesIgnoringSafeArea(.all)
List {
Text("Bla bla bla")
.listRowBackground(backgroundColor)
Group {
VStack {
TextField("Server address", text: $serverAddress)
.keyboardType(.default)
TextField("Server port", text: $serverPortString)
.keyboardType(.numberPad)
}
}
.listRowBackground(backgroundColor)
.padding()
.background(Color.white)
.cornerRadius(8)
// Some more elements
}
}
.navigationBarHidden(false)
.navigationBarTitle("Connect your Server", displayMode: .large)
}
.onTapGesture {
print("tapped")
}
}
}
Which will give you this result:

Resources