How to extend the width of a button using SwiftUI - ios

I cannot figure out how to change the width of buttons in SwiftUI.
I have already attempted:
using .frame(minWidth: 0, maxWidth: .infinity),
using Spacer() around the button and navigationlink,
using frame on the Text field and padding on the button, look through the documentation, as well as a few other things I found while just searching online. However nothing changes the buttons width whatsoever.
NavigationLink(destination: Home(), isActive: self.$isActive) { Text("") }
Button(action: { self.isActive = true }) { LoginBtn() }
struct LoginBtn: View {
var body: some View {
Text("Login")
.fontWeight(.bold)
.padding()
.foregroundColor(Color.white)
.background(Color.orange)
.cornerRadius(5.0)
}
}
Photo of current button
I would like to have the button to extend to be similar to the width of the TextFields used. Again, I know there have been answers posted but for some reason I cannot get mine to work. Thanks!

Declare your own button style:
struct WideOrangeButton: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.frame(minWidth: 0,
maxWidth: .infinity)
.foregroundColor(.white)
.padding()
.background( RoundedRectangle(cornerRadius: 5.0).fill(Color.orange)
)
}
}
and then use it like this:
Button(action: { self.isActive = true }) {
Text("Login")
.fontWeight(.bold)
} .buttonStyle(WideOrangeButton())

I like this approach since it lets me use the default button style, but still results in a wider button.
Button(action: {
// Whatever button action you want.
}, label: {
Text("Okay")
.frame(maxWidth: .infinity)
})
.buttonStyle(.automatic)

Related

SwiftUI add `menu` in `.safeAreaInset` cause strange layout issue

Here is the sample project source code: sample code
import SwiftUI
struct TestMenuInSafeAreaInset: View {
#State private var message = ""
var body: some View {
VStack {
Rectangle()
.fill(Color.blue)
}
.safeAreaInset(edge: .bottom) {
HStack {
TextField("Input your message", text: $message)
.padding()
.background(Color.brown)
.cornerRadius(12)
.foregroundColor(.white)
Menu {
Button {
} label: {
Text("Confirm")
}
Button {
} label: {
Text("Cancel")
}
} label: {
Image(systemName: "square.and.arrow.up.fill")
.tint(.white)
.padding()
.background(Color.brown)
.cornerRadius(50)
}
}
.padding()
}
}
}
struct TestMenuInSafeAreaInset_Previews: PreviewProvider {
static var previews: some View {
TestMenuInSafeAreaInset()
}
}
When keyboard appear, the action menu button (right-bottom corner) shift up a little, and tap the menu will cause strange layout as the gif shown.
I think this is a bug, any solution to fix it? I test above code with iOS 16 and iOS 15 with same behaviour.
[Updated 2022.10.10 11:31 +8]
As #Saket Kumar 's solution, I update the code as below, the issue is reproduced even I give size to the menu.
Test with iPhone 14 pro simulator iOS 16.
struct TestMenuInSafeAreaInset: View {
#State private var message = ""
var body: some View {
VStack {
TextField("Input your user name", text: $message)
.padding()
.background(Color.gray.opacity(0.3))
.cornerRadius(12)
.padding()
Spacer()
}
.safeAreaInset(edge: .bottom) {
HStack {
Spacer()
.frame(height: 70)
Menu {
Button {
} label: {
Text("Confirm")
}
Button {
} label: {
Text("Cancel")
}
} label: {
Image(systemName: "square.and.arrow.up.fill")
.padding()
.tint(.white)
.background(Color.brown)
.cornerRadius(50)
}
.frame(width: 50, height: 50)
}
.padding(.horizontal, 20)
.background(Color.blue)
}
}
}
Seems an issue with SwiftUI. I tested your code and I was able to reproduce the issue.
I had my hunch that this weird behaviour may be caused by TextField's Frame, and Menu's frame overlapping, which SwiftUI is trying to accommodate.
So I tried giving them frame manually, and it seems to fix the issue.
Just change this portion of the code.
.safeAreaInset(edge: .bottom) {
HStack {
TextField("Input your message", text: $message)
.padding()
.background(Color.brown)
.cornerRadius(12)
.foregroundColor(.white)
.frame(width: UIScreen.main.bounds.width*0.75, height: 50, alignment: .leading)
Spacer()
Menu {
Button {
} label: {
Text("Confirm")
}
Button {
} label: {
Text("Cancel")
}
} label: {
Image(systemName: "square.and.arrow.up.fill")
.tint(.white)
.padding()
.background(Color.brown)
.cornerRadius(50)
}.frame(width: UIScreen.main.bounds.width*0.10, height: 50, alignment: .trailing)
}
.padding()
}
Fair warning. Those frames I have put may not be exactly as you want. I have tested this code It works.
[Just added your code in demo project to simulate it]
My suggestion would be to give fixed width, height to Menu say 60*60. Then take out 60 from the screen's width, account for padding. And give suitable frame to TextField.

Is there a chance to add a collapsable text via a dedicated button?

I just started with SwiftUI and wanted to build a simple home app. In order to have a better overview I structured my site using a collapsible view, which when expanded reveals the home view. However, I've been struggling to make a dedicated "plus" button that adds another one of the predefined collapsable views to my Content View
Here is the code I made (with the help of a tutorial) for the CollapsableViewModel:
var body: some View {
ZStack{
VStack {
HStack{
Button(
action: { self.collapsed.toggle() },
label: {
HStack {
TextField("Empty...", text: $textFieldText)
.font(.title2.bold())
Spacer()
Image(systemName: self.collapsed ? "chevron.down" : "chevron.up")
}
.padding(.bottom, 1)
.background(Color.white.opacity(0.01))
}
)
.buttonStyle(PlainButtonStyle())
}
.padding(1)
}
VStack {
self.content()
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: collapsed ? 0 : .none)
.clipped()
.transition(.slide)
}
}
}
And here's my Content View:
var body: some View {
ScrollView{
HStack{
CollapsableViewModel(
label: { Text("") .font(.title2.bold()) },
content: {
HStack {
Text("turn off light.")
Text("turn on ac.")
Spacer()}
.frame(maxWidth: .infinity)
}
)
.frame(maxWidth: .infinity)
}
.padding()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.statusBar(hidden: false)
.navigationBarHidden(true)
}
Now, the problem is that I really don't know where to start with this. My guess is that I have to work with an button that triggers a "showCollapsView" action. But I don't how I make it so that it appears under the VStack of my main ContentView. Any tipps would be appreciated, as I would love to understand this whole process myself!

SwiftUI Picker in Form - Can't Dynamically Size the Form Space

I'm struggling with a view where I want to have multiple pickers embedded in
other views. When I wrap the pickers in a Form, I get the desired behavior for the
picker but there is a lot of extra space around the pickers that I can't seem to
automatically adjust.
This is an example - the space in the red outline seems to be determined by the other
view elements not the size of the picker.
I can, of course, hard-code a frame height for the Form but that is trial and error
and would only be specific to the device and orientation. I have tried multiple
versions of Stacks inside Stacks with padding, GeometryReader etc, but I have not come up with any
solution. As an aside, I DO want the picker labels, otherwise I could just remove
the Form.
I also tried setting UITableView.appearance().tableFooterView in an init() but that did not work either.
Here is a simplified version:
struct ContentView4: View {
#State var selectedNumber1: Int = 1
#State var selectedNumber2: Int = 2
#State var selectedNumber3: Int = 3
var body: some View {
NavigationView {
VStack(alignment: .leading) {
HStack {
Spacer()
Text("Compare up to 3")
.font(.caption)
Spacer()
}//h
Form {//for pickers
Picker(selection: $selectedNumber1, label: Text("A")) {
ForEach(0..<10) {
Text("\($0)")
}
}//picker
Picker(selection: $selectedNumber2, label: Text("B")) {
ForEach(0..<10) {
Text("\($0)")
}
}//picker
Picker(selection: $selectedNumber3, label: Text("C")) {
ForEach(0..<10) {
Text("\($0)")
}
}//picker
}//form for pickers
.padding(.horizontal, 10)
//.frame(height: 200) //don't want to hard code this
VStack(alignment: .leading) {
HStack {
Text("A")
.frame(width: 100)
Text("B")
.frame(width: 100)
Text("C")
.frame(width: 100)
}
.padding(.horizontal, 10)
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading){
Text("A title line")
.font(.headline)
.padding(.vertical, 5)
HStack {
Text("Number")
.frame(width: 100)
Text("Number")
.frame(width: 100)
Text("Number")
.frame(width: 100)
}
Text("Another title line")
.font(.headline)
.padding(.vertical, 5)
HStack {
Text("Something")
.frame(width: 100)
Text("Something")
.frame(width: 100)
Text("Something")
.frame(width: 100)
}
Text("A Third title line")
.font(.headline)
.padding(.vertical, 5)
HStack {
Text("More")
.frame(width: 100)
Text("More")
.frame(width: 100)
Text("More")
.frame(width: 100)
}
}
}//scroll
.padding(.horizontal, 10)
}
.navigationBarTitle("Compare Three", displayMode: .inline)
}
}//nav
}//body
}//struct
Interestingly, I am able to get a solution by removing the form and wrapping each
picker in a menu, like this:
Menu {
Picker(selection: $selectedNumber2, label: EmptyView()) {
ForEach(0..<10) {
Text("\($0)")
}
}//picker
} label: {
HStack {
Text("B")
Spacer()
Image(systemName: "chevron.right")
.resizable()
.frame(width: 14, height: 14)
}//h
}//menu label
However, I still like the look of the Form better if I could automatically configure
the space around the Form items.
Any guidance would be appreciated. Xcode 13.4, iOS 15.5
Form (and List) is not meant to be stacked inside other views like this, which is why it has such strange behavior.
Thankfully, it's fairly simple to recreate the stuff you do want using NavigationLink. Here’s a quick example of a couple custom views that do just that:
// drop-in NavigationLink replacement for Picker
struct NavigationButton<Content: View, SelectionValue: Hashable> : View {
#Binding var selection: SelectionValue
#ViewBuilder let content: () -> Content
#ViewBuilder let label: () -> Text
var body: some View {
NavigationLink {
PickerView(selection: $selection, content: content, label: label)
} label: {
HStack {
label()
Spacer()
Text(String(describing: selection))
.foregroundColor(.secondary)
}
.contentShape(Rectangle())
}
.buttonStyle(NavigationLinkButtonStyle())
}
}
// subview for the Picker page, which lets us use `dismiss()`
// to pop the subview when the user selects an option
struct PickerView<Content: View, SelectionValue: Hashable> : View {
#Binding var selection: SelectionValue
#ViewBuilder let content: () -> Content
#ViewBuilder let label: () -> Text
#Environment(\.dismiss) private var dismiss
var body: some View {
Form {
Picker(selection: $selection, content: content, label: label)
.pickerStyle(.inline)
.labelsHidden()
.onChange(of: selection) { _ in
dismiss()
}
}
.navigationTitle(label())
}
}
// recreate the appearance of a List row
struct NavigationLinkButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
configuration.label
.frame(maxWidth: .infinity)
Image(systemName: "chevron.right")
.font(.footnote.bold())
.foregroundColor(Color(UIColor.tertiaryLabel))
}
.padding()
.background(
Rectangle()
.fill(configuration.isPressed ? Color(UIColor.quaternaryLabel) : Color(UIColor.systemBackground))
)
}
}
If you like the .insetGrouped style you got using Form, we can replicate that by putting NavigationButton inside a clipped VStack:
VStack(spacing: 0) {
NavigationButton(selection: $selectedNumber1) {
ForEach(0..<10) {
Text("\($0)")
}
} label: {
Text("A")
}
Divider()
NavigationButton(selection: $selectedNumber2) {
ForEach(0..<10) {
Text("\($0)")
}
} label: {
Text("B")
}
}
.clipShape(RoundedRectangle(cornerRadius: 11))
.padding()
.background(Color(UIColor.systemGroupedBackground))
And here’s a screenshot showing my custom views above your original Form.
(And if you like Picker as a popup menu, you could use Menu instead of NavigationLink)

SwiftUI - How to put TextField in navigation bar like settings app

In the native Settings app, there's a NavigationView with a TextField inside of it that nicely transitions as the user scrolls:
I was able to create something similar using:
struct HomeView: View {
#State var searchQuery: String = ""
var body: some View {
NavigationView {
List {
TextField("Search", text: $searchQuery).textFieldStyle(RoundedBorderTextFieldStyle())
}
.navigationBarTitle(Text("My App"))
}
}
}
which gave me this:
However, this doesn't really look or act the same as the native settings one, and I'm lost on how to even get the search icon in there. Thanks so much!
What youre trying to create in SwiftUI would be a UISearchBar in swift's UIKit.
So you need to stylize the textfield
TextField("Search ...", text: $text)
.padding(7)
.padding(.horizontal, 25)
.background(Color(.systemGray6))
.cornerRadius(8)
.padding(.horizontal, 10)
.onTapGesture {
self.isEditing = true
}
And in order to achieve the magnifying glass icon which is standard for a UISearchBar item. We need to add them manually with an overlay in SwiftUI
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.gray)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 8)
if isEditing {
Button(action: {
self.text = ""
}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
)
you can reference this article for more https://www.appcoda.com/swiftui-search-bar/

Can't format text in Alert SwiftUI

I would like to modify the font size and color of the text in an Alert in SwiftUI. Adding
modifiers does not seem to work. I must be missing something simple here. I created
the most basic of alert screens, added text modifiers and they are ignored. I created
my own view to show the kind of result I would like. Obviously, since I can make what
I want, I could go that route though it is a lot of work and it just seems like the
built-in alert ought to be able to do this.
struct ContentView: View {
#State private var showAlert = false
#State private var showMyAlert = false
var body: some View {
GeometryReader { geo in
ZStack {
VStack {
Text("Make Some Font Business")
.font(.title)
.foregroundColor(.red)
Button(action: {
self.showAlert.toggle()
}) {
Text("Toggle System Alert")
}
Button(action: {
self.showMyAlert.toggle()
}) {
Text("Show MyAlert")
}
}
if self.showMyAlert {
MyAlert(showMyAlert: self.$showMyAlert)
.animation(.easeInOut)
}
}//vstack
.frame(width: geo.size.width, height: geo.size.height)
.background(self.showMyAlert ? Color.gray.opacity(0.2) : Color.white)
.alert(isPresented: self.$showAlert) {
Alert(title: Text("Important"),
message: Text("This text should be large and it should be green")
.font(.system(size: 36))
.foregroundColor(.green),
dismissButton: .default(Text("Ok")))
}//.alert
}//geo
.edgesIgnoringSafeArea(.all)
}
}
struct MyAlert: View {
#Binding var showMyAlert: Bool
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20)
.frame(width: 275, height: 180, alignment: .center)
.foregroundColor(.white).opacity(1.0)
VStack {
Text("Important")
//.fontWeight(.bold)
.font(.system(size: 20))
Divider()
Text("This text should be large and it should be green")
.font(.system(size: 20))
.foregroundColor(.green)
.multilineTextAlignment(.center)
Divider()
Button(action: {
self.showMyAlert.toggle()
} ) {
Text("Ok")
.foregroundColor(.blue)
.font(.system(size: 20))
}
}//vstack
.frame(width: 225, height: 150, alignment: .center)
}//zstack
}
}
Any guidance would be appreciated.
Xcode 11.3.1 (11C504)
As I know modifiers did not work on build-in Alert in SwiftUI. It's a standard system font and size to show on default alert view and not changeable like UIKit default alert. I think the best way is implementing the custom modifier to show the custom alert

Resources