How to wrap Text around some view in a HStack? - ios

I wanted to ask if following scenario would be possible and if yes how I could approach the problem. The following code produces the attached image:
HStack(alignment: .firstTextBaseline) {
ZStack {
RoundedRectangle(cornerRadius: 5)
.foregroundColor(Color(UIColor.secondarySystemFill))
Text("Test")
.clipShape(RoundedRectangle(cornerRadius: 5))
.foregroundColor(.secondary)
.layoutPriority(1)
.padding(.all, 5)
}
Text("This is a very long message with more words than one line can handle bla blabla blablabl")
}
Now in order to save more space I would like to have the next lines move to the left like so:
I have considered following approaches but none got me very far:
Using Swift UIs Text() + Text() instead of the HStack. This would not work as this method does not allow background colors (a .background() would converter the Text() to some View and therefore I can't combine it with another Text()). I could only change the .foregroundColor.
Maybe I could somehow write a UIKit wrapper for a UILabel with NSAttributedString. I don't like this method very much though, as changing background colors with NSAttributedString isn't a very good solution either.
Use a ZStack and maybe somehow throw a .clipShape() onto the longer right hand Text() so that it moves a little more to the right. This approach is also quite hacky since I don't quite know how to calculate the length of the first string so that I could move the second string.
Either I am missing something or this just isn't something that you could do in Swift UI or UIKit.

Related

Get frame/dimensions from SwiftUI view(s)

Let's assume, to present a specific piece of information I have two different kinds of custom SwiftUI views. For the sake of an example my data is two Strings and the options to display them is either in a
HStack { Text() Spacer() Text() }
or
VStack {
Text()
Text()
}
style. In order to select the best fitting one, I would need to render them and make a choice based on resulting dimensions. For instance, if one of the text views in the first style would approach 50% of the window size, I would rather go with the second style.
How would I go about this without the user seeing the temporary views?
I know about GeometryReader, but I don't know how I could render my "candidate views" off screen, determine sizes and then make a selection for my actual view hierarchy.
Any hints?
I don't know how to work properly with SwiftUI. However, the following is an approach for what you want using UIKit and Labels for text:
let max_width = UIScreen.main.bounds.width/2
if label.intrinsicContentSize.width > max_width{
//The text would occupy more than 50% of the screen in width
}else{
//The text won't occupy more than 50% of the screen in width
}
You would have to run the previous function on each Label and there you can decide.
I know this is not a complete answer because you are working with SwiftUI, but someone may know how to apply the previous code on there.

SwiftUI Xcode 12.5 with very basic NavigationView layout Issues

I have been developing iOS for about a decade and every time I try to take the dive into SwiftUI I spend more time than ever wrestling what should seemingly be a simple task. While working on an app with very simple navigation setup I kept seeing two errors in the console: Unable to present. Please file a bug. and Unbalanced calls to begin/end appearance transitions for <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVVS_22_VariadicView_Children7ElementGVS_18StyleContextWriterVS_19SidebarStyleContext___: 0x7fd913d0bd90>. The first happens when there are at least 3 Views to navigate from (I don't understand why this is a significant threshold and my end goal uses a LazyVGrid with a ForEach) with navigation links and the second error happens on rotating to landscape and then back to portrait. I believed this to be related to how the phone is presenting the sidebar but even changing to StackNavigationViewStyle produced similar problems.
If this were a UIKit application I can absolutely solve for the Unbalanced calls situation but SwiftUI really takes away some of the lower level capabilities that I am used to having control of when it comes to building Views and navigation stacks.
I finally attempted to just start a new project from scratch and place the minimal amount of code in the ContentView:
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Number 1")) {
Text("Number 1")
}
NavigationLink(destination: Text("Number 2")) {
Text("Number 2")
}
NavigationLink(destination: Text("Number 3")) {
Text("Number 3")
}
}
}
}
}
Running the above code produced the issues on rotation. Another issue that I came across was when you press the < back button after these issues start, the navigation stops working completely and the "detail" view never gets updated.
It is clear that the direction is SwiftUI so I am trying to really go this direction (maybe next week will have some amazing improvements) but this seems to be a pretty significant issue on a very simple set of code. I am hoping that I am just doing something wrong that someone can point out quickly.
EDITED:
After more exploration I found that the second error happens on the 11, 11 Pro Max, and 12 Pro Max where the navigation stack changes to the sidebar by default. Changing the style to StackNavigationViewStyle does eliminate the second error (but doesn't help if I do want to use the sidebar style) but the first error remains. To Schottky's point, changing VStack to List will also eliminate the first error. However a newer convention (based on WWDC videos at least) to solve for collection views I believe is to use a LazyV/HGrid with a ForEach within it which is actually what I am attempting to accomplish. I didn't put that as my code here since I wanted the be able to reproduce the error in the simplest form of course to ensure it wasn't something buried in my view hierarchy.
The way I was able to accomplish this was via a post I found at HackingWithSwift here. I still had to use .navigationViewStyle(StackNavigationViewStyle()) to eliminate a different error as it seems that the initial iterations of SwiftUI focuses on the 80% of cases where multiple NavigationLinks only really exist in the List View type. I have not tested this with the latest beta but if you try to use the other navigation style (Column) it will throw another error: unbalanced calls to begin/end appearance transactions. I am okay with this for now as this at least allows me to create a screen that does not have line separators and navigation arrows....I just don't have the Master-Detail setup by default.

SwiftUI LazyVGrid animating change of "page"

I’m trying to treat an entire LazyVGrid as pages, and animate when switching forward or back. A simple slide animation would be fine.
I currently have something along the lines of
LazyVGrid(
columns: [array of column info],
alignment: .center,
spacing: 4
) {
ForEach(cells) { cell in
CellView(cell: cell)
}
}
I have pages of cells that get set on the state when you hit the fwd or back buttons, and they are immediately re-rendered. However, it would be cool to set a forward/back slide when the buttons are hit. I haven’t been able to figure this out easily with transition and animation.
If there’s an entirely different library doing this, I’d be open to trying it.
Thanks so much!

A single component's animation is messing up the whole view — SwiftUI

I'm building a SwiftUI app for my wife. Her avatar pulses with a repeating animation. It looks cool and seems to work just fine on its own. This is a component that lives in its own SwiftUI file.
When I bring a bunch of the components together to create a view, however, the animation messes it all up.
What a mess, right?
I assumed this happened because I did not define the width of the view. I used the fix from this issue, but it didn't make a difference.
I'm feeling pretty stuck here. Here's the repo for the project, with the code for this view. Does anyone have an idea for how I can fix this animation issue?
You need to remove the animation(nil) in the AvatarComponent
You also need to change all .frame(width: 352) to .frame(width: UIScreen.main.bounds.size.width)
The answer from E.Coms above was very helpful! But instead of replacing the width (325) of all my UI elements, I appended .frame(width: UIScreen.main.bounds.size.width) to the top-level wrapper. It seems to work just fine now!

Swift UI List: Open external URL when cell is tapped

I am trying to open a URL when one of the List's cells is tapped. I tried adding the modifier onTapGesture to the cell itself and then calling UIApplication.shared.open(url), but this only works if the tap is right on the cell view's elements (and not on the cell's background).
I also tried to add a background view (Rectangle) to the cell with opacity 0.01, but although this works the Rectangle is quite visible despite its low opacity.
Is there any workaround to make the whole row tappable?
Found a solution, here it is in case it helps anyone in the future:
// edit:
Used a single Button, with the required action (i.e. openURL in my case) in the action closure, and with my custom view returned in the label closure.
#stakri, What you're looking for is ".contentShape()"
Rectangle()
.stroke()
.onTapGesture() {
UIApplication.shared.open(URL(string: "https://stackoverflow.com")!)
}
above code will only work if you tap on the 'stroke' outline of the rectangle, but .contentShape() will make the entire area tappable without the need to nest it inside of a Stack:
Rectangle()
.stroke()
.contentShape( Rectangle() )
.onTapGesture() {
UIApplication.shared.open(URL(string: "https://stackoverflow.com")!)
}
Others coming to this question will likely be looking for how to specifically open a URL, you'll notice I force unwrapped my URL. Open to feedback on that, but barring any issues brought up, this works well.

Resources