Post

Replies

Boosts

Views

Activity

Error when previewing on device
When the Xcode Previews app opens on the device, this is the error message in Xcode: RemoteHumanReadableError: Failed to update preview. Error encountered when sending 'display' message to agent. I tried cleaning the build folder and quitting then reopening Xcode to no avail. Using Xcode 12.0.1 previewing on iPhone 11.
18
0
9.2k
Jan ’23
Using Core Data objects with Transferable
I was wondering whether objects in Core Data (and CloudKit) conform, or are able to be conformed, to the Transferable protocol. As far as I can see there is no underlying implementation yet, but maybe this will be added as a future feature so that SwiftUI and Core Data can work better together. In the WWDC22 session "Enhance collaboration experiences with Messages" at 10:21, a struct call Note was implementing the transferRepresentation required property and returned an object of type CKShareTransferRepresentation from its body. I couldn't find any reference to this type anywhere in the documentation and nothing else was mentioned in the session video. Maybe this is something that is going to be added soon or was removed after the video was made. Since I want to use Core Data in my SwiftUI app and want to enable sharing features, such as collaboration via the shared database, NSManagedObject subclasses need some way of conforming to the Transferable protocol. I was hoping there would be a specialised way to do this, and the aforementioned type from the session video sort of hinted at this. I am just asking here to see if anyone has any information about this – whether this feature is about to be released, how this issue can be solved, or another way to do this. Any help is appreciated.
1
5
2.2k
Aug ’22
Load and save image from document directory
I have added two methods to an extension of URL so I can load and save and images. extension URL { func loadImage(_ image: inout UIImage) { if let loaded = UIImage(contentsOfFile: self.path) { image = loaded } } func saveImage(_ image: UIImage) { if let data = image.jpegData(compressionQuality: 1.0) { try? data.write(to: self) } } } I use this extension in a view: @State private var image = UIImage(systemName: "xmark")! private var url: URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0].appendingPathComponent("image.jpg") } var body: some View { Image(uiImage: image) .onAppear { url.load(&image) } .onTapGesture { url.save(image) } } However this isn't working. The image isn't loaded from the document directory because its probably isn't being saved. Is there anyway to rewrite this extension or another alternative to loading and saving a UIImage? Or is this just a bug with Xcode 12/iOS 14?
3
1
8.7k
Jun ’22
Custom Font Picker Accessing UIFont Properties Crashes App
I am attempting to create a custom font picker (similar to the one in Pages) using SwiftUI, because the current UIFontPickerViewController isn't sufficient enough for my app. When running the app and presenting FontPickerView in a sheet, the app seems to pause, the sheet doesn't appear, and a lot of dialog continuously pops up in the Xcode console. This is an example of what keeps showing: CoreText note: Client requested name ".SFUI-Regular", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:]. The .SFUI string changes with different font styles, for example -Bold, -Compressed, -SemiExpandedLight... I believe the problem lies when accessing the UIFont family and font name properties and methods. Is there a reason why this is happening? A possible solution? Help is appreciated. Here is some code you can test (Xcode 13 beta 3): extension Character {     var isUppercase: Bool {         String(self).uppercased() == String(self)     } } extension UIFont { // Will show dialog from here     class func familyName(forFontName fontName: String) -> String {         var familyName = ""         familyNames.forEach { family in             fontNames(forFamilyName: family).forEach { font in                 if font == fontName {                     familyName = family                 }             }         }         return familyName     } } struct FontPickerView: View {     @Environment(\.dismiss) private var dismiss     @ScaledMetric private var linkPaddingLength = 24     @State private var searchText = ""     @State private var linkSelection: String?     @Binding var selectedFontName: String // Will show dialog from here     private var familyNames: [String] {         UIFont.familyNames.filter {             $0.contains(searchText) || searchText.isEmpty         }     } // Will show dialog from here     private var familyPickerBinding: Binding<String> {         Binding {             UIFont.familyName(forFontName: selectedFontName)         } set: {             selectedFontName = UIFont.fontNames(forFamilyName: $0)[0]         }     }     var body: some View {         NavigationView {             List {                 Picker("All Fonts", selection: familyPickerBinding) {                     ForEach(familyNames, id: \.self, content: pickerRow)                 }                 .labelsHidden()                 .pickerStyle(.inline)             }             .listStyle(.insetGrouped)             .searchable(text: $searchText, placement: .navigationBarDrawer)             .navigationTitle("Fonts")             .navigationBarTitleDisplayMode(.inline)             .toolbar {                 Button("Cancel", action: dismiss.callAsFunction)             }         }     }     private func linkPadding(forFamilyName familyName: String) -> CGFloat {         familyPickerBinding.wrappedValue == familyName ? 0 : linkPaddingLength     }     private func familyText(forFamilyName familyName: String) -> some View {         Text(familyName)             .font(.custom(familyName, size: UIFont.labelFontSize))     }     private func familyTextWithStyles(forFamilyName familyName: String) -> some View {         ZStack(alignment: .leading) {             NavigationLink("Style options", tag: familyName, selection: $linkSelection) {                 FontStylesView(selection: $selectedFontName, family: familyName)             }             .hidden()             HStack {                 familyText(forFamilyName: familyName)                 Spacer()                 Button(action: { linkSelection = familyName }) {                     Label("Style options", systemImage: "info.circle")                         .labelStyle(.iconOnly)                         .imageScale(.large)                 }                 .buttonStyle(.borderless)                 .padding(.trailing, linkPadding(forFamilyName: familyName))             }         }     }     private func pickerRow(forFamilyName familyName: String) -> some View {         Group {             if UIFont.fontNames(forFamilyName: familyName).count == 1 {                 familyText(forFamilyName: familyName)             } else {                 familyTextWithStyles(forFamilyName: familyName)             }         }     } } struct FontStylesView: View {     @Binding var selection: String     let family: String     var body: some View {         List {             Picker("Font Styles", selection: $selection) { // Will show dialog from here                 ForEach(UIFont.fontNames(forFamilyName: family), id: \.self) { font in                     Text(fontType(forFontName: font))                         .font(.custom(font, size: UIFont.labelFontSize))                 }             }             .labelsHidden()             .pickerStyle(.inline)         }         .navigationTitle(family)     }     private func fontType(forFontName fontName: String) -> String {         if let index = fontName.lastIndex(of: "-") {             var text = String(fontName.suffix(from: index).dropFirst())             // Add spaces between words.             let indexes = text.enumerated().filter { $0.element.isUppercase }.map { $0.offset }             var count = 0             indexes.forEach { index in                 guard index > 0 else { return }                 text.insert(" ", at: text.index(text.startIndex, offsetBy: index + count))                 count += 1             }             return text         } else {             return "Regular"         }     } } (There are a few bugs that I am going to fix.)
2
0
2.4k
Apr ’22
Move and delete in ForEach without List
Here is my code simplified. struct TileView: View { @Binding var editMode: EditMode var columns = [GridItem(.adaptive(minimum: UIScreen.main.bounds.width / 4))] var body: some View { LazyVGrid(columns: columns, spacing: 16) { ForEach(0 ..< 5, id: \.self) { num in ZStack(alignment: .topLeading) { GroupBox(label: Text("Label")) { Text("Content") } .contextMenu { Button { } label: { Label("Delete", systemImage: "trash") } } // this is the work around for the delete action if editMode == .active { Button { } label: { Label("Delete", systemImage: "minus.circle.fill") .imageScale(.large) .foregroundColor(Color(.systemRed)) .backgroundColor(Color(.systemFill) .clipShape(Circle()) .labelStyle(IconOnlyLabelStyle()) .offset(x: -10, y: -10) } } } .padding(.horizontal, 4) } } } .padding(.horizontal) } } Is there any way I can add an .onMove or .onDelete modifier to the ForEach and have those actions work when editing, or something else similar (maybe implementing a List to make it work)? If not, is there a workaround for the move action (since I already have a delete action workaround)? Thanks in advance for any solutions.
1
0
2k
Apr ’22
Preferred Actions in Alerts
Is there any way to set preferred actions for alerts in SwiftUI? You can set .cancel roles for alert buttons, but they appear in bold and I want the other preferred action to be in bold. I could set the preferred action to have the .cancel role, but I don't think you're supposed to do it like that. I haven't found a proper way yet, but I haven't played around with alerts enough to know. Thanks for any suggestions.
2
0
4.6k
Aug ’21
Countdown timer picker with minutes and seconds
I am trying to replicate the timer picker from the Clock app, shown below, using SwiftUI. DatePicker doesn't have a countDownTimer mode like UIDatePicker does, but then that doesn't show seconds even though the countDownDuration property is in seconds. I am currently trying to use a custom UIPickerView with two components (minutes and seconds), all wrapped inside a UIViewRepresentable. This sort of works, but I can't seem to get the min and sec labels to be positioned where they are. Any help on this matter would be much appreciated.
2
0
3.6k
Jul ’21
List Row Separator Insets
I think that the list row separator insets needs to be fixed in SwiftUI. For example, when using the .sidebar list style in a compact environment, the separators are inset to a fixed position, and depending on the list row's content, will look normal or out of place. In one of last year's session videos (wwdc20-10026), Apple even said how to use separators properly, insetting them to align with the primary content of the cell. If there is a way that I don't know of to control this, I would very much like to know. Otherwise this needs to be sorted either introducing a new view modifier, or automatically deciding how much to inset by based on the list row content: with Label, inset to align with the title.
1
0
1.6k
Jun ’21
Change Xcode theme based on appearance
I have decided to try out a light theme in Xcode (don’t ask why), when light mode is on, and then use a dark theme when the system switches to dark mode. However, when Xcode goes dark, the editor stays with the light theme and doesn’t switch to an equivalent dark one. I would like to know if there is a way to have Xcode automatically do this - for example, in light mode use Presentation (Light) and in dark mode use Presentation (Dark). As of yet, I haven’t found a solution within Xcode, but maybe there is a way to control this by using a custom theme?
0
1
1.7k
May ’21
Error when previewing on device
When the Xcode Previews app opens on the device, this is the error message in Xcode: RemoteHumanReadableError: Failed to update preview. Error encountered when sending 'display' message to agent. I tried cleaning the build folder and quitting then reopening Xcode to no avail. Using Xcode 12.0.1 previewing on iPhone 11.
Replies
18
Boosts
0
Views
9.2k
Activity
Jan ’23
Using Core Data objects with Transferable
I was wondering whether objects in Core Data (and CloudKit) conform, or are able to be conformed, to the Transferable protocol. As far as I can see there is no underlying implementation yet, but maybe this will be added as a future feature so that SwiftUI and Core Data can work better together. In the WWDC22 session "Enhance collaboration experiences with Messages" at 10:21, a struct call Note was implementing the transferRepresentation required property and returned an object of type CKShareTransferRepresentation from its body. I couldn't find any reference to this type anywhere in the documentation and nothing else was mentioned in the session video. Maybe this is something that is going to be added soon or was removed after the video was made. Since I want to use Core Data in my SwiftUI app and want to enable sharing features, such as collaboration via the shared database, NSManagedObject subclasses need some way of conforming to the Transferable protocol. I was hoping there would be a specialised way to do this, and the aforementioned type from the session video sort of hinted at this. I am just asking here to see if anyone has any information about this – whether this feature is about to be released, how this issue can be solved, or another way to do this. Any help is appreciated.
Replies
1
Boosts
5
Views
2.2k
Activity
Aug ’22
Load and save image from document directory
I have added two methods to an extension of URL so I can load and save and images. extension URL { func loadImage(_ image: inout UIImage) { if let loaded = UIImage(contentsOfFile: self.path) { image = loaded } } func saveImage(_ image: UIImage) { if let data = image.jpegData(compressionQuality: 1.0) { try? data.write(to: self) } } } I use this extension in a view: @State private var image = UIImage(systemName: "xmark")! private var url: URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0].appendingPathComponent("image.jpg") } var body: some View { Image(uiImage: image) .onAppear { url.load(&image) } .onTapGesture { url.save(image) } } However this isn't working. The image isn't loaded from the document directory because its probably isn't being saved. Is there anyway to rewrite this extension or another alternative to loading and saving a UIImage? Or is this just a bug with Xcode 12/iOS 14?
Replies
3
Boosts
1
Views
8.7k
Activity
Jun ’22
Custom Font Picker Accessing UIFont Properties Crashes App
I am attempting to create a custom font picker (similar to the one in Pages) using SwiftUI, because the current UIFontPickerViewController isn't sufficient enough for my app. When running the app and presenting FontPickerView in a sheet, the app seems to pause, the sheet doesn't appear, and a lot of dialog continuously pops up in the Xcode console. This is an example of what keeps showing: CoreText note: Client requested name ".SFUI-Regular", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:]. The .SFUI string changes with different font styles, for example -Bold, -Compressed, -SemiExpandedLight... I believe the problem lies when accessing the UIFont family and font name properties and methods. Is there a reason why this is happening? A possible solution? Help is appreciated. Here is some code you can test (Xcode 13 beta 3): extension Character {     var isUppercase: Bool {         String(self).uppercased() == String(self)     } } extension UIFont { // Will show dialog from here     class func familyName(forFontName fontName: String) -> String {         var familyName = ""         familyNames.forEach { family in             fontNames(forFamilyName: family).forEach { font in                 if font == fontName {                     familyName = family                 }             }         }         return familyName     } } struct FontPickerView: View {     @Environment(\.dismiss) private var dismiss     @ScaledMetric private var linkPaddingLength = 24     @State private var searchText = ""     @State private var linkSelection: String?     @Binding var selectedFontName: String // Will show dialog from here     private var familyNames: [String] {         UIFont.familyNames.filter {             $0.contains(searchText) || searchText.isEmpty         }     } // Will show dialog from here     private var familyPickerBinding: Binding<String> {         Binding {             UIFont.familyName(forFontName: selectedFontName)         } set: {             selectedFontName = UIFont.fontNames(forFamilyName: $0)[0]         }     }     var body: some View {         NavigationView {             List {                 Picker("All Fonts", selection: familyPickerBinding) {                     ForEach(familyNames, id: \.self, content: pickerRow)                 }                 .labelsHidden()                 .pickerStyle(.inline)             }             .listStyle(.insetGrouped)             .searchable(text: $searchText, placement: .navigationBarDrawer)             .navigationTitle("Fonts")             .navigationBarTitleDisplayMode(.inline)             .toolbar {                 Button("Cancel", action: dismiss.callAsFunction)             }         }     }     private func linkPadding(forFamilyName familyName: String) -> CGFloat {         familyPickerBinding.wrappedValue == familyName ? 0 : linkPaddingLength     }     private func familyText(forFamilyName familyName: String) -> some View {         Text(familyName)             .font(.custom(familyName, size: UIFont.labelFontSize))     }     private func familyTextWithStyles(forFamilyName familyName: String) -> some View {         ZStack(alignment: .leading) {             NavigationLink("Style options", tag: familyName, selection: $linkSelection) {                 FontStylesView(selection: $selectedFontName, family: familyName)             }             .hidden()             HStack {                 familyText(forFamilyName: familyName)                 Spacer()                 Button(action: { linkSelection = familyName }) {                     Label("Style options", systemImage: "info.circle")                         .labelStyle(.iconOnly)                         .imageScale(.large)                 }                 .buttonStyle(.borderless)                 .padding(.trailing, linkPadding(forFamilyName: familyName))             }         }     }     private func pickerRow(forFamilyName familyName: String) -> some View {         Group {             if UIFont.fontNames(forFamilyName: familyName).count == 1 {                 familyText(forFamilyName: familyName)             } else {                 familyTextWithStyles(forFamilyName: familyName)             }         }     } } struct FontStylesView: View {     @Binding var selection: String     let family: String     var body: some View {         List {             Picker("Font Styles", selection: $selection) { // Will show dialog from here                 ForEach(UIFont.fontNames(forFamilyName: family), id: \.self) { font in                     Text(fontType(forFontName: font))                         .font(.custom(font, size: UIFont.labelFontSize))                 }             }             .labelsHidden()             .pickerStyle(.inline)         }         .navigationTitle(family)     }     private func fontType(forFontName fontName: String) -> String {         if let index = fontName.lastIndex(of: "-") {             var text = String(fontName.suffix(from: index).dropFirst())             // Add spaces between words.             let indexes = text.enumerated().filter { $0.element.isUppercase }.map { $0.offset }             var count = 0             indexes.forEach { index in                 guard index > 0 else { return }                 text.insert(" ", at: text.index(text.startIndex, offsetBy: index + count))                 count += 1             }             return text         } else {             return "Regular"         }     } } (There are a few bugs that I am going to fix.)
Replies
2
Boosts
0
Views
2.4k
Activity
Apr ’22
Move and delete in ForEach without List
Here is my code simplified. struct TileView: View { @Binding var editMode: EditMode var columns = [GridItem(.adaptive(minimum: UIScreen.main.bounds.width / 4))] var body: some View { LazyVGrid(columns: columns, spacing: 16) { ForEach(0 ..< 5, id: \.self) { num in ZStack(alignment: .topLeading) { GroupBox(label: Text("Label")) { Text("Content") } .contextMenu { Button { } label: { Label("Delete", systemImage: "trash") } } // this is the work around for the delete action if editMode == .active { Button { } label: { Label("Delete", systemImage: "minus.circle.fill") .imageScale(.large) .foregroundColor(Color(.systemRed)) .backgroundColor(Color(.systemFill) .clipShape(Circle()) .labelStyle(IconOnlyLabelStyle()) .offset(x: -10, y: -10) } } } .padding(.horizontal, 4) } } } .padding(.horizontal) } } Is there any way I can add an .onMove or .onDelete modifier to the ForEach and have those actions work when editing, or something else similar (maybe implementing a List to make it work)? If not, is there a workaround for the move action (since I already have a delete action workaround)? Thanks in advance for any solutions.
Replies
1
Boosts
0
Views
2k
Activity
Apr ’22
Destructive actions and separators in SwiftUI Menu
Is there any way to add destructive actions (such as a delete button in red) or separators to the new Menu in iOS and iPadOS as shown in the Build/Design with iOS pickers, menus and actions talks? There's no way that I know of with .contextMenu and I was wondering if there was a way or a workaround.
Replies
3
Boosts
0
Views
5.9k
Activity
Aug ’21
Preferred Actions in Alerts
Is there any way to set preferred actions for alerts in SwiftUI? You can set .cancel roles for alert buttons, but they appear in bold and I want the other preferred action to be in bold. I could set the preferred action to have the .cancel role, but I don't think you're supposed to do it like that. I haven't found a proper way yet, but I haven't played around with alerts enough to know. Thanks for any suggestions.
Replies
2
Boosts
0
Views
4.6k
Activity
Aug ’21
Countdown timer picker with minutes and seconds
I am trying to replicate the timer picker from the Clock app, shown below, using SwiftUI. DatePicker doesn't have a countDownTimer mode like UIDatePicker does, but then that doesn't show seconds even though the countDownDuration property is in seconds. I am currently trying to use a custom UIPickerView with two components (minutes and seconds), all wrapped inside a UIViewRepresentable. This sort of works, but I can't seem to get the min and sec labels to be positioned where they are. Any help on this matter would be much appreciated.
Replies
2
Boosts
0
Views
3.6k
Activity
Jul ’21
List Row Separator Insets
I think that the list row separator insets needs to be fixed in SwiftUI. For example, when using the .sidebar list style in a compact environment, the separators are inset to a fixed position, and depending on the list row's content, will look normal or out of place. In one of last year's session videos (wwdc20-10026), Apple even said how to use separators properly, insetting them to align with the primary content of the cell. If there is a way that I don't know of to control this, I would very much like to know. Otherwise this needs to be sorted either introducing a new view modifier, or automatically deciding how much to inset by based on the list row content: with Label, inset to align with the title.
Replies
1
Boosts
0
Views
1.6k
Activity
Jun ’21
Change Xcode theme based on appearance
I have decided to try out a light theme in Xcode (don’t ask why), when light mode is on, and then use a dark theme when the system switches to dark mode. However, when Xcode goes dark, the editor stays with the light theme and doesn’t switch to an equivalent dark one. I would like to know if there is a way to have Xcode automatically do this - for example, in light mode use Presentation (Light) and in dark mode use Presentation (Dark). As of yet, I haven’t found a solution within Xcode, but maybe there is a way to control this by using a custom theme?
Replies
0
Boosts
1
Views
1.7k
Activity
May ’21