Post not yet marked as solved
Let's say I have a SwiftUI view that's a compose experience, like composing a new email in Mail, an iMessage in Messages, or a Tweet in Twitter.
When the view is loaded, I want the soft keyboard to appear automatically so that the user can type immediately without needing to manually put focus in the TextField or TextEditor by tapping on it.
With the new @FocusState feature in iOS 15, I can programmatically put focus on different TextFields when the user interacts elsewhere in the UI (like pressing a button), but I can't seem to set a default focus.
I tried initializing focus in the SwiftUI view's init method as well as the onAppear method attached to other parts of the view, but this didn't seem to have any effect.
How can I put default focus on a TextField or TextEditor when a view is loaded?
Post not yet marked as solved
I developing a swiftUI app for macOS. I like the side bar very much. It shows up on the left and I can add a button to open and close it. All this is good. However, I also like a similar panel on the right, so it can serve as an 'inspector' to the content I am editing.
It looks like a right sidebar may not be supported in SwiftUI. So, I tried the following:
NavigationView() {
// Sidebar
VStack(alignment: .leading) {
// My sidebar views here
}
.frame(minWidth: 200, idealWidth: 220, maxWidth: 240)
// Main Content
VStack {
ScrollView {
LazyVGrid() {
// My Grid view here
}
}
}
// Inspector View
VStack(alignment: .leading) {
// Inspector views here
}
.frame(minWidth: 200, idealWidth: 220, maxWidth: 240)
}
My desire was for the Inspector view will be snapped to the right and the main content to fill the center space. The above layout doesn't do that. Instead, the inspector view appears much wider and the main content shrunk.
I can use the divider to resize it accoding to my need. But would love for it to appear as desired on startup.
Is there any other way or workaround I can explore to achieve this?
Post not yet marked as solved
I have this sample code:
struct Item: Identifiable {
var id = UUID()
var name: String?
}
struct ItemTable: View {
let items: [Item]
var body: some View {
Table(items) {
TableColumn("Name", value: \.name)
}
}
}
I get the following error:
Key path value type 'String?' cannot be converted to contextual type 'String'
I can solve using \.name!, but I'd like to give a default value instead (something like \.name ?? "default").
How can I achieve this?
Hi, thanks for adding markdown support in SwiftUI's Text with Xcode 13 and iOS 15! :)
Even formatting like strikethrough works!
Text("Hello ~~World~~")
So which specification is supported?? This goes apparently beyond Commonmark (as strikethrough is not part of Commonmark specification). Is it GitHub Flavored Markdown or even a different spec?
Post not yet marked as solved
I have been unable to install iOS 15 beta on an iPhone 6S.
I first updated the device to iOS 14.6. I downloaded the iOS 15 Beta Software Profile and installed it. Under Settings > Software Update, I can see the beta.
Selecting "Install Now" shows "Verifying update..." for about 5 minutes and then a generic error. "Unable to Install Update". An error occurred installing iOS 15 Developer beta. Retry / Remind Me Later.
I looked at Console and didn't see any useful errors. The iOS developer beta is 4.66GB, and so my phone is currently at 14.3GB out of 16GB. Is this a disk space issue with an unhelpful error messages? Anything else I should try?
Post not yet marked as solved
Text in iOS 15 Beta 1 (Xcode 13 Beta 1) only handles markdown when string literal was passed to initializer.
struct MarkdownTest: View {
var text: String = "**Hello** *World*"
var body: some View {
VStack {
Text("**Hello** *World*") // will be rendered with markdown formatting
Text(text) // will NOT be rendered according to markdown
}
}
}
struct MarkdownTestPreviews: PreviewProvider {
static var previews: some View {
MarkdownTest()
}
}
Is this a known bug or do I have to create an entry in Feedback Assistant?
Using Xcode 13 beta 2:
In my SwiftUI preview code I add previewInterfaceOrientation like so:
static var previews: some View {
Group {
Preview()
#if swift(>=5.5)
if #available(iOS 15.0, *) {
Group {
Preview()
}
.previewInterfaceOrientation(.landscapeRight)
}
#endif
}
}
With this code and running on an iOS 14 device the app crashes immediately with dyld: Symbol not found: _$s7SwiftUI4ViewPAAE27previewInterfaceOrientationyQrAA0eF0VFQOMQ
It would seem I can't use this handy interface orientation option in Previews until the app's minimum target is iOS 15. It seems like a bug in the framework because that symbol should be considered optional as it is surrounded by if #available.
Why does a swipe action (using the new .swipeAction in SwiftUI 5.5, currently beta 3) set editMode? Notice when you swipe that "Edit" changes to "Done"?
And yet this is not like full edit mode because tapping the EditButton shows the move handles (and the ever-annoying ugly blank indentation for the absent onDelete modifier).
I think my next project won't use SwiftUI.
import SwiftUI
struct Fruit: Identifiable {
let id: UUID = UUID()
let name: String
let color: Color
}
struct ListingView: View {
@State var fruits: [Fruit] = [
Fruit(name: "banana", color: .yellow),
Fruit(name: "apple", color: .green),
Fruit(name: "tomato", color: .red)]
@Environment(\.editMode) private var editMode
var body: some View {
NavigationView {
VStack(alignment: .leading) {
List {
ForEach(fruits) { fruit in
NavigationLink(
destination: ZStack {
fruit.color
Text(fruit.name).bold().font(.largeTitle)
}
.navigationTitle(fruit.name),
label: {
HStack(alignment: .center) {
fruit.color.frame(width: 30, height: 30)
Text(fruit.name)
}
})
.swipeActions(edge: .leading, allowsFullSwipe: false) {
Button(action: { delete(fruit) },
label: { Image(systemName: "trash") }).tint(.red)
}
}
.onMove(perform: { from, to in
fruits.move(fromOffsets: from, toOffset: to)
})
}
}
.navigationBarTitle("Fruits")
.toolbar {
ToolbarItem(placement: .primaryAction) {
EditButton()
}
}
}
}
private func delete(_ fruit: Fruit) {
guard let index = fruits.firstIndex(where: {$0.id == fruit.id}) else { return }
fruits.remove(at: index)
}
}
struct ListingView_Previews: PreviewProvider {
static var previews: some View {
ListingView()
}
}
Post not yet marked as solved
privacySensitive() doesn't work.
This is my code:
VStack {
Text("Card number")
.font(.headline)
Text("123 456 789")
.font(.headline)
.privacySensitive()
}
}
Simulator Version:
Version 13.0 (969)
SimulatorKit 612
CoreSimulator 775
Xcode version:
Version 13.0 beta 4 (13A5201i)
Post not yet marked as solved
ForEach reshuffle the array object to the last which has been changed from ObservableObject in SwiftUI.
Post not yet marked as solved
I have done the same thing in SwiftUI using UIViewRepresentable, but toolPicker doesn't show so I checked isFirstResponder property and I found that it was still false after I called canvas.becomeFirstResponder().
Check this out:
struct NoteCanvasView: UIViewRepresentable {
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.drawingPolicy = .anyInput
canvas.delegate = context.coordinator.self
let toolPicker = PKToolPicker()
toolPicker.setVisible(true, forFirstResponder: canvas)
toolPicker.addObserver(canvas)
print(canvas.canBecomeFirstResponder)
canvas.becomeFirstResponder()
print(canvas.isFirstResponder)
return canvas
}
func updateUIView(_ canvas: PKCanvasView, context: Context) {
canvas.becomeFirstResponder()
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: NoteCanvasView
init(_ parent: NoteCanvasView) {
self.parent = parent
}
}
}
I found canvas.canBecomeFirstResponder returns true and canvas.isFirstResponder always returns false.
Is this a bug in current version of SwiftUI??
Post not yet marked as solved
What the hell is this? I code a view in Xcode 13 beta 5 and run it in iOS 15 beta 6. I don't understand what these error message mean, please help!
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
import SwiftUI
@available(iOS 15.0, *)
struct ExerciseEditView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@State var headerTitle: String = "Count"
@State var name: String = ""
@State var count: Int = 0
@State var min: Int = 0
@State var sec: Int = 0
@State var weight: Int = 0
var body: some View {
Form{
Section("Name"){
TextField("name", text: $name, prompt: Text("name"))
}
Section(self.headerTitle){
Picker("pickTime", selection: $headerTitle){
Text("Count")
.tag("Count")
Text("Time")
.tag("Time")
}
.pickerStyle(.segmented)
if self.headerTitle == "Time" {
Picker("time", selection: $min){
ForEach(0...60, id:\.self){value in
Text("\(value)")
.tag(value)
}
}
.pickerStyle(.wheel)
.frame(height: 60)
}else {
Picker("count", selection: $count){
ForEach(0...100, id:\.self){value in
Text("\(value)")
.tag(value)
}
}
.pickerStyle(.wheel)
.frame(height: 60)
}
}
Section("Weight"){
Picker("weight", selection: $weight){
ForEach(0...500, id:\.self){value in
Text("\(value)")
.tag(value)
}
}
.pickerStyle(.wheel)
.frame(height: 60)
}
}
.navigationTitle("Exercise")
.navigationBarTitleDisplayMode(.large)
.navigationBarItems(trailing: HStack{
Button(action:{
presentationMode.wrappedValue.dismiss()
}){
Text("Done")
}
})
}
}
Post not yet marked as solved
I try UIDevice, but occurred error :
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
error:
2021-08-23 11:54:05.514193+0800 Spider-IOS[5696:1212060] [error] precondition failure: setting value during update: 805944
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
AttributeGraph precondition failure: setting value during update: 805944.
Post not yet marked as solved
Hey!
It seems that Label used in the menu construction is wrapped in a system button and there is no way to change it– for example I’d like to display only the image and the image only (SFSymbol to be exact). With macOS 12 I can turn off the menu indicator or set the menuStyle (or even use custom style but the API is extremely limited; for example the Configuration doesn’t expose the label or body instances) but I can’t change the font size (of the button, not of the menu ofc) of the symbol…
Does anyone figured it out?
I am using a @SectionedFetchRequest with some success.
This sectioned fetch request feeds data to a List().
I want to include a footer to the list that provides a count of the managed objects returned from the sectioned fetch request.
Previously I have used .count.
This still works but only returns the number of sections.
A sectioned fetch request provides this result...
SectionedFetchResults<String, CoreDataEntityClass>
So how do I iterate through this unusual collection to determine a count?
Post not yet marked as solved
According to WWDC video and documentation this code should work:
Menu {
Button(action: addCurrentTabToReadingList) {
Label("Add to Reading List", systemImage: "eyeglasses")
}
Button(action: bookmarkAll) {
Label("Add Bookmarks for All Tabs", systemImage: "book")
}
Button(action: show) {
Label("Show All Bookmarks", systemImage: "books.vertical")
}
} label: {
Label("Add Bookmark", systemImage: "book")
} primaryAction: {
addBookmark()
}
However when I try it, it throws an error: Extra argument in call for primaryAction
any ideas?
(latest beta MacOS, and latest Xcode)
Post not yet marked as solved
I have been trying to use the new @Binding capabilities in SwiftUI but every time I make a ForEach and pass binding values, when the TextField changes, the keyboard unfocuses the Field.
struct ContentView: View {
@State private var texts: [String] = ["Orange", "Apple"]
var body: some View {
NavigationView {
List {
ForEach($texts, id: \.self) { $text in
TextField("Fruit", text: $text)
}
}
.navigationTitle("Fruit List")
}
.navigationViewStyle(.stack)
}
}
That is what I have tried, is there an error in my implementation or is it just a bug?
My Mac:
MacMini 2020 - M1 16GB
Xcode 13.0 - (13A233)
Project Built - for iOS 15
Post not yet marked as solved
I am working on a shopping app with firestore as a backend, where users add products to the cart.(Shop -> Product Category -> Product -> Add to cart). There is some weird behavior when the user clicks on the add to cart button. For the first time when the user clicks on Add to cart, the view automatically pops back to the Product category screen. Then if I click on any product category it goes to the product screen and pops back automatically. I am stuck with this issue for a couple of days, Please shed some light on what I am doing wrong. Thanks a ton.
Product
@DocumentID var id : String?
var name : String?
var price : String?
var available : Bool = false
var quantity : Int = 1
var category : String?
enum CodingKeys: String, CodingKey {
case id, name, price, category, available
}
}
ProductViewModel
@Published var productArray : [Product] = []
@Published var selectedProducts : [Product] = []
@Published var productTotal = ProductTotal(totalAmt: 0)
@Published var productImgDict : [String : String] = [:]
@Published var selectedProduct = Product()
@Published var cartResponse : CartResponse?
@Published var isCartRespReceived : Bool = false
@Published var checkoutResponse : CheckOutResponse?
@Published var isCheckOutResReceived : Bool = false
var products : [Product] = []
var dummyProductLst : [Product] = []
var dummyCartItems : [Product] = []
var firestore = Firestore.firestore()
var storageRef = Storage.storage()
init(){
isCartRespReceived = false
}
func setSelectedProduct(product : Product) {
selectedProducts.append(product)
self.dummyCartItems.append(product)
self.setDefaultProductQty(product: product)
}
func setDefaultProductQty(product : Product) {
for index in self.selectedProducts.indices {
if product.id == self.selectedProducts[index].id {
//By default setting the quantity to 1 when adding a product
self.selectedProducts[index].quantity = +1
}else{
print("not matched")
}
}
}
func getSelectedProduct() -> [Product] {
return self.selectedProducts
}
func deleteProduct(index : IndexSet) {
self.selectedProducts.remove(atOffsets: index)
self.dummyCartItems.remove(atOffsets: index)
}
func getTotalAmount() -> ProductTotal {
var totalAmt = 0;
for item in self.selectedProducts {
totalAmt = totalAmt + Int(item.price?.floatValue ?? 0)
}
return ProductTotal( totalAmt: totalAmt)
}
func setQuantity(index : Int, qty : Int = 1) {
self.selectedProducts[index].quantity = qty
}
func setgetUpdatedPrice(index : Int, qty : Int, itemID : String = "") -> String {
var calculatedAmt = 0
if let data = self.dummyCartItems.first(where: {$0.id == itemID}) {
calculatedAmt = Int(data.price?.floatValue ?? 0) * qty
self.selectedProducts[index].price = String(calculatedAmt)
} else {
// item could not be found
}
_ = getTotalAmount()
print(calculatedAmt)
return String(calculatedAmt)
}
}
ProductGridView
@EnvironmentObject var prodViewModel : ProductViewModel
@EnvironmentObject var partialSheetManager : PartialSheetManager
@Binding var showToast : Bool
var product : Product
var store : Store
var body: some View {
ZStack(alignment: Alignment(horizontal: .trailing, vertical: .top)){
VStack(alignment: .center, spacing: 10){
let imgURL = prodViewModel.productImgDict[product.id ?? ""]
AnimatedImage(url: URL(string: imgURL ?? "")).resizable().frame(width: 110, height: 110).padding()
HStack{
Text("₹\(product.price ?? "")")
.foregroundColor(Color.theme.appColor)
.font(.title2).bold()
Spacer(minLength: 20)
if product.available {
Button(action: {
if self.prodViewModel.getSelectedProduct().contains(where: { $0.id == product .id}){
//item found
}else{
// not found in cart - add product to array
if store.id == AppSettings.shared.getStoreID(){
prodViewModel.setSelectedProduct(product: product)
showToast = true
}else{
print("shop is different, you cannot add it")
self.partialSheetManager.showPartialSheet {
ChangeShopView(store: store, product: product)
}
}
}
}, label: {
Image.init(systemName: "cart.badge.plus")
.renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.original))
.resizable()
.frame(width: 32, height: 30)
}
)
}else{
}
}
HStack{
Text(product.name ?? "")
.font(.title3)
.multilineTextAlignment(.leading)
.foregroundColor(Color.theme.textColor)
Spacer()
}
} .overlay(
Text( product.available ? "" : "NOT AVAILABLE")
.foregroundColor(.white)
.background(Color.red)
.font(.caption)
.clipShape(RoundedRectangle(cornerRadius: 4))
.padding(.horizontal)
,alignment: .center)
.padding(.horizontal, 8)
.frame(width : UIScreen.main.bounds.size.width/2.4)
.background(Color.theme.cardColor)
.cornerRadius( 6)
.shadow(color: Color.black.opacity(0.2), radius:5, x:-5, y:5)
}
}
}
On clicking Add to cart button I am calling the setSelectedProduct method from ProductViewModel. In the console, am getting - Unable to present. Please file a bug.
Post not yet marked as solved
I am trying to use the solution provided by you but this doesn’t work. Can you please help me ?
Post not yet marked as solved
Hi guys,
I try to use .searchable to add search bar to a list, see my code as below, but it doesn't work. How can I make it work? Somebody, please help me!!!
import SwiftUI
@available(iOS 15.0, *)
struct ContentView: View {
var body: some View {
NavigationView {
TabView{
VStack{
List{
Text("aaa")
Text("bbb")
Text("ccc")
}
.searchable(text: .constant(""))
}
.tabItem({
Text("tab1")
})
VStack{
Text("tab2")
}
.tabItem({
Text("tab2")
})
}
}
}
}
@available(iOS 15.0, *)
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}